我想测试散列中的元素是否存在以及是否> = 0,然后将true或false放入数组中:
boolean_array << input['amount'] && input['amount'] >= 0
Run Code Online (Sandbox Code Playgroud)
这在NilClass错误上引发no> =.但是,如果我这样做:
input['amount'] && input['amount'] >= 0 #=> false
Run Code Online (Sandbox Code Playgroud)
没问题.基本上:
false && (puts 'what the heck?') #=> false
arr = []
arr << false && (puts 'what the heck?') #=> stdout: 'what the heck?'
arr #=> [false]
Run Code Online (Sandbox Code Playgroud)
是什么赋予了?
目前它被分组为:
(boolean_array << input['amount']) && input['amount'] >= 0
Run Code Online (Sandbox Code Playgroud)
尝试:
boolean_array << (input['amount'] && input['amount'] >= 0)
Run Code Online (Sandbox Code Playgroud)
但是,如果它最终为false,则表达式返回nil,因此您需要:
boolean_array << (!input['amount'].nil? && input['amount'] >= 0)
Run Code Online (Sandbox Code Playgroud)
&& 总是在Ruby中评估短路.
问题出 在优先级<<之前&&,请参阅Rubydoc:优先级
所以行
arr << false && (puts 'what the heck?')
Run Code Online (Sandbox Code Playgroud)
实际上是:
(arr << false) && (puts 'what the heck?')
Run Code Online (Sandbox Code Playgroud)