Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to push a value to an array with a ternary operator?

Tags:

ruby

the array is returning a boolean value instead of the value assigned by the ternary operator

and the code...

arr = []
arr <<  true == false ? 'a' : 'b'
# Expecting, the output of arr to be ['b']. But instead, I was getting [true] 

Why is this behavior?

and to get the right value I have to do this.

arr << if true == false
         'a'
       else
         'b'
       end  

# and also, = also works fine
arr =  true == false ? 'a' : 'b' # arr has 'b'

and why the behavior is different when using the ternary operator?

like image 548
Ravi Avatar asked Dec 03 '22 10:12

Ravi


2 Answers

It is due to Ruby's operator precedence. Operator << has greater precedence than the ternary operator. Your example can be solved by modifying the code as below:

arr = []
arr << (true == false ? 'a' : 'b')
like image 55
the_spectator Avatar answered Jan 20 '23 11:01

the_spectator


thank you all for helping, I like the solution by iGian i.e. without parenthesis.

arr <<= true == false ? 'a' : 'b'

like image 39
Ravi Avatar answered Jan 20 '23 11:01

Ravi