"unless" keyword

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 :slight_smile:

Thanks in advance,
Mike.

Mike Novecento schrieb:

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 :slight_smile:

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

Thank you all.