Quantcast
Channel: Active questions tagged return-value - Stack Overflow
Viewing all articles
Browse latest Browse all 206

Ruby quirk: Using 'return' to get a nil value

$
0
0

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 } end

the 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 }

Viewing all articles
Browse latest Browse all 206

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>