I am doing a problem at Rubymonk where I have to test if an array is 'nil' before doing an operation (adding items inside a nested array but that is not really relevant to the question). I notice, however, if I enter an empty array:
ary.nil? ? nil : ary.map {|x,y=0| x + y }The code returns 'nil' as desired, but if I do
ary.nil? ? return nil : ary.map {|x,y=0| x + y }it no longer works.
However, if I do
if ary.nil? return nil else ary.map {|x,y=0| x + y } endthe code works as expected and again returns 'nil'.
Why does return nil work in the last instance but not in the ternary expression?
I would have expected the expression return nil to work in both instances.
UPDATE: Thank you @ShadowRanger. Using parentheses in the ternary addresses my concern. Much appreciated!
ary.nil? ? (return nil) : ary.map {|x,y=0| x + y }