Monday, January 14, 2008

Ruby method return values

There is a generalization in ruby that the last expression evaluated will be the return value from a method if no explicit return is specified. The Ruby Pickaxe states in Chapter 6, "The return value of a method is the value of the last expression executed or the result of an explicit return expression."

Although this is generally true, it can bite you as this is not exactly the case.

For example, consider the following:
>> def test1
>> a=5 if true
>> end
=> nil

>> test1
=> 5
That looks ok, and the return value of 5 shouldn't surprise you as that was the last expression evaluated. Now how about this (below)? What is the last expression evaluated here?
>> def test2
>> a=5 if false
>> end
=> nil

>> test2
=> nil
Did you expect that result? I didn't. I would say 'false' is the last expression evaluated, so I would expect the return value to be false. But instead of false, I get nil.

Why? It would seem that expressions evaluated as the controlling expression of a conditional statement (if, unless, etc.) don't count as an implied return value.

Let's simplify this even more:
>> def test3
>> if 2 > 3
>> end
>> end
=> nil

>> test3
=> nil
So it would appear it doesn't matter. And again...
>> def test4
>> if 3 > 2
>> end
>> end
=> nil

>> test4
=> nil
Yep, ruby doesn't care about conditional statement controlling expressions with respect to return values.

Happy ruby'ing!

No comments: