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!


Anonymous said...

Queen Casino Resort Coupons for 2021 | Free Shipping | Katsu-Tek
Queen Casino Resort Coupons | 카지노사이트 Exclusive $219 Off With EXCLUSIVE 20% Off Hotel Bookings Last December, クイーンカジノ they ミスティーノ sold over 23 million units at a valuation

sabenetadeo said...

How to play Slots from the casino in NJ - Dr.MCD
The 안양 출장마사지 slots is a great way to 전라남도 출장마사지 play with friends 김제 출장안마 and 김천 출장안마 family. With the help of our Live Dealer dealers, you can have fun with all the action 양산 출장샵 of the

Unknown said...

Alisia Casino - Jordan Sports
Alisia where to find air jordan 18 retro men red Casino offers a full casino experience. The main focus is air jordan 18 retro yellow online shop the online what is the best jordan 18 white royal blue casino in which you can play slot machines for free, no download how to get air jordan 18 retro men required! show to buy air jordan 18 retro men