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?
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')
thank you all for helping, I like the solution by iGian i.e. without parenthesis.
arr <<= true == false ? 'a' : 'b'
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