PoVa PoVa - 1 year ago 41
Ruby Question

Does ruby stop evaluating if statements when first condition is false?

Does ruby stop evaluating if statements when first condition is false? I constantly get

undefined method `ready' for nil:NilClass>
song = nil

if !song.nil? && song.ready && !song.has_been_downloaded_by(event.author)
elsif !song.ready
"The song is not ready yet. Try again once it is."
elsif song.has_been_downloaded_by(event.author)
"Yo, check your private messages, I've already sent you the song."
'Song with such index does not exist.'

Answer Source

Ruby, and most other programming languages use short circuiting boolean expressions. Meaning any expression of the form false && puts("hi") will not run the right side of the expression puts("hi"). This goes for if conditions as well, anything with && really.

This is specially important to know because you always want to put faster or cheaper expressions/functions on the left side and more expensive expressions on the right side of a && operator.

Consider this

puts "hi" if expensive_method() && some_value

In the above example expensive_method will always run. But what if some_value is sometimes false? This would be more efficient:

puts "hi" some_value && expensive_method()

Taking advantage of the possibility that some_value might sometimes be false, we spare ourselves from having to evaluate expensive_method in those cases.

In short, take advantage of boolean expression short circuiting.