"unless" keyword

M

Mike Novecento

Ok guys, you convinced me: Ruby is the way to go. I have been reading
online for a few hours now, and it looks simply fantastic (especially
with Ruby on Rails).
I am so excited, I have been programming for years, and never thought
it could be so fun.

I have a first question. Looking at some code online, I have seen this
line of code from a the site of pragmatic programmer:

errors.add:)price, "should be positive") unless price.nil? || price >
0.0

I understand that it is required to validate that a price is strictly
positive.
My question, maybe very easy, is... how does it exactly work?

I thought it should be "ADD ERROR unless NOT NIL AND PRICE > 0.0"...
why he uses (OR) ||? Maybe I am missing the logic of the keyword
"unless". I feel dumb :)

Thanks in advance,
Mike.
 
P

Pit Capitain

Mike said:
I have a first question. Looking at some code online, I have seen this
line of code from a the site of pragmatic programmer:

errors.add:)price, "should be positive") unless price.nil? || price >
0.0

I understand that it is required to validate that a price is strictly
positive.
My question, maybe very easy, is... how does it exactly work?

I thought it should be "ADD ERROR unless NOT NIL AND PRICE > 0.0"...
why he uses (OR) ||? Maybe I am missing the logic of the keyword
"unless". I feel dumb :)

Hi Mike,

in code like this:

<signal error> if <condition>

you have to write down the condition for the error, whereas in

<signal error> unless <condition>

you express the condition you want to assert. Most of the time I prefer
the second form. In the code you've shown above, you can easily read the
required properties right after the "unless" keyword without having to
do more boolean logic than necessary: the price has to be nil (left
empty) or positive.

Regards and welcome to Ruby,
Pit
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,801
Messages
2,569,658
Members
45,419
Latest member
NereidaChe

Latest Threads

Top