Newbie Code question

No. 0 is not nil.

irb(main):001:0> a = nil => nil irb(main):002:0> a.nil? => true irb(main):003:0> a = 0 => 0 irb(main):004:0> a.nil? => false

Ugh, how I hate "unless"...

Unless is like "if not". So...

errors.add() <if not> (price.nil? || price > 0.0)

So, when your price is <= 0.0...

errors.add() <if not> (false || false) # since price.nil? is false, and price > 0.0 is false

errors.add() <if not> (false) # since (false || false) is false

so errors are added.

Thanks for the replies guys. So, what would be a more sensible way to write that line?

Thanks in advance.

I would say something like:

errors.add(:price, "should be positive") if !price.nil? && price <= 0.0

Or, to be a bit more verbose:

if !price.nil? if price <= 0.0    errors.add(:price, "should be positive") end end

I guess that's not a huge improvement. Basically, one way or another, you have to check whether price is nil first, and then, if it isn't, check whether it's less than or equal to 0, and that's what makes the line a bit complicated. Hope this helps!

Why not...

errors.add(:price, "should be positive") if price.to_f < 0

This should work since...

nil.to_f

=> 0.0

Or,

errors.add(:price, "should be positive") if !(price > 0)

-Nathan

Oops, sorry. Just realised nil is supposed to be a valid answer.

errors.add(:price, "should be positive") if !(price > 0 || price.nil?)

-Nathan

It’s actuall a question posed to the object

something.nil?

The method includes the ?

It says to the object “Hey, are you nil?”