为什么 Ruby 中的 && 有时会进行快捷方式评估,有时不会?

  • 本文关键字:评估 快捷方式 Ruby 中的 ruby
  • 更新时间 :
  • 英文 :


我想测试哈希中是否存在元素,如果它>=0,那么将true或false放入数组:

boolean_array << input['amount'] && input['amount'] >= 0

这在NilClass错误上引发no>=。然而,如果我只是这样做:

input['amount'] && input['amount'] >= 0   #=> false

没问题。基本上:

false && (puts 'what the heck?') #=> false
arr = []
arr << false && (puts 'what the heck?') #=> stdout: 'what the heck?'
arr #=> [false]

什么东西?

<<的优先级高于&&。请参阅Ruby运算符优先级。

目前它被分组为:

(boolean_array << input['amount']) && input['amount'] >= 0

尝试:

boolean_array << (input['amount'] && input['amount'] >= 0)

但是,如果它最终为false,则表达式将返回nil,因此您需要:

boolean_array << (!input['amount'].nil? && input['amount'] >= 0)

&&在Ruby中总是被评估为短路。

问题是<<优先于&&,请参阅Rubydoc:优先

所以线路

arr << false && (puts 'what the heck?')

实际上是:

(arr << false) && (puts 'what the heck?')

最新更新