I want to test if an element in a hash exists and if it is >= 0, then put true or false into an array:
boolean_array << input['amount'] && input['amount'] >= 0
This raises no >= on NilClass error. However, if I just do this:
input['amount'] && input['amount'] >= 0 #=> false
No problem. Basically:
false && (puts 'what the heck?') #=> false
arr = []
arr << false && (puts 'what the heck?') #=> stdout: 'what the heck?'
arr #=> [false]
What gives?
<< has more precedence than &&. See Ruby Operator Precedence.
Currently it's being grouped as:
(boolean_array << input['amount']) && input['amount'] >= 0
Try:
boolean_array << (input['amount'] && input['amount'] >= 0)
However, if it ends up being false, the expression returns nil, so you want:
boolean_array << (!input['amount'].nil? && input['amount'] >= 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With