You don't need to return explicitly!
Ruby returns the value of the last line executed.
Don't do this:
def foo
value = Foo.first(:conditions => { :label => "bar" })
return value
end
Do this instead:
def foo
Foo.first(:conditions => { :label => "bar" })
end
Leave feedback...
Commenting is closed for this article.

Thats quite an interesting feature. However, it makes me wonder; Does this mean you sometimes end up with returned values when you don’t really want one?
Yep, it will return things when you don’t necessarily want a return value. I’ve never explicitly wanted nothing returned though – for methods that don’t return something interesting most of the time I just don’t care what’s returned so returning whatever is last evaluated is good enough.
Right, I was more thinking along the lines of somebody using your code and they don’t know if they should be doing something with the returned value or not…
That’s a fair concern, but I’ve never run across the problem either in code that I’ve written or code that I talk to. If it’s not documented or it’s untested then it shouldn’t be relied on.
I can’t remember where I saw the benchmarks, but returning explicitly is apparently slower as well.
Explicit returns are only slower in ruby 1.8.x. There’s no appreciable penalty in 1.9 or JRuby