Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does && in Ruby sometimes shortcut evaluates and sometimes doesnt?

Tags:

ruby

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?

like image 985
jz999 Avatar asked Dec 29 '25 17:12

jz999


2 Answers

<< has more precedence than &&. See Ruby Operator Precedence.

like image 135
Sony Santos Avatar answered Jan 01 '26 07:01

Sony Santos


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)
like image 31
Jorge Israel Peña Avatar answered Jan 01 '26 07:01

Jorge Israel Peña



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!