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...

  1. 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?

  2. 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.

  3. 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…

  4. 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.

  5. I can’t remember where I saw the benchmarks, but returning explicitly is apparently slower as well.

  6. Explicit returns are only slower in ruby 1.8.x. There’s no appreciable penalty in 1.9 or JRuby

Commenting is closed for this article.

About the boy

A picture of Craig in grayscale

Craig Webster is a software engineer living in London. He usually works with Ruby although sometimes he sneaks in some Erlang or JavaScript. He's into rock climbing, snowboarding, skating, photography and fencing. Yes, this does mean he has a sword.

Near here you'll find Craig's homepage, contact details, PGP key and keysigning policy, and talks.

Licence

The entire content of this blog is public domain. Use it however you fancy. You don't even need to attribute it to me, although it would be nice if you did. Just don't sue me and we'll all be happy.

I Work With Rails

Recommend Me

My Travels

I go places. Do you go places too? Let's meet up!.