当第一个条件为假时,ruby是否会停止评估if语句?

PoV*_*oVa 7 ruby

当第一个条件为假时,ruby是否会停止评估if语句?我不断地得到undefined method `ready' for nil:NilClass>song = nil.

    if !song.nil? && song.ready && !song.has_been_downloaded_by(event.author)
      song.send_to_user(event.author)
      nil
    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."
    else
      'Song with such index does not exist.'
    end
Run Code Online (Sandbox Code Playgroud)

Die*_*zar 7

Ruby和大多数其他编程语言都使用短路布尔表达式.意味着表单的任何表达式false && puts("hi")都不会运行表达式的右侧puts("hi").这也适用于if条件,任何&&真正的条件.

这一点特别重要,因为您总是希望在左侧放置更快或更便宜的表达式/函数,在&&操作员右侧放置更昂贵的表达式.

考虑一下

puts "hi" if expensive_method() && some_value
Run Code Online (Sandbox Code Playgroud)

在上面的例子expensive_method中将始终运行.但如果some_value有时会假的呢?这会更有效:

puts "hi" if some_value && expensive_method()
Run Code Online (Sandbox Code Playgroud)

利用some_value有时可能是错误的可能性,我们不必expensive_method在这些情况下进行评估.

简而言之,利用布尔表达式短路.

https://en.wikipedia.org/wiki/Short-circuit_evaluation