I’ve noticed this little oddity(I think) in If Statements in Ruby. Here’s an example:
my_number = nil
if my_number < 3
'number is less than 3'
end
Obviously, when you run this code you’ll get a “comparison of Fixnum with nil failed” error. Now here’s something strange. If I make a little change in the If Statement to check for nil, it works fine. Example:
my_number = nil
if my_number && my_number < 3
'number is less than 3'
end
Adding the check for nil makes it not crash. This may all sound stupid but I can’t figure out why that works. Shouldn’t it still throw an error?
Thanks to anyone who can explain this. 🙂 Thanks!
Boolean expressions are evaluated in what is known as “short circuit” fashion. That is, as soon as it know the result, it doesn’t keep trying to evaluate expressions.
So it does the
if my_numberand since that’sfalse, there is no need to continue, becausefalse && <anything>is always false.This is a useful language feature, and many languages work like this (the original Visual Basic is one exception that I can think of) because it lets you do exactly this sort of test without requiring cumbersome nested ‘if’s.