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)
"The song is not ready yet. Try again once it is."
"Yo, check your private messages, I've already sent you the song."
'Song with such index does not exist.'
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
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
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.