Reputation: 10944
Would you prefer this:
def add(a, b)
puts "ADDING #{a} + #{b}"
return a + b
end
over this?
def add(a, b)
puts "ADDING #{a} + #{b}"
a + b
end
Upvotes: 3
Views: 438
Reputation: 77816
It's The Ruby Way™ to not include the return
statement unless it's absolutely required.
I'm sure there's better examples, but here's a simple one.
def divide a, b
return false if b == 0
a/b
end
It's worth noting that Ruby provides means to optionally ignore a lot of syntax. ()
are optional unless you're nesting them. {}
can be omitted in many cases too.
func(5, 5, {:hello => 'world'})
# is the same as
func 5, 5, hello: 'world'
You'll learn a lot more shortcuts as you go.
Upvotes: 4
Reputation: 11
take a look at this: http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
it explains how return works on procs, lambdas and blocks.
Upvotes: 1
Reputation: 23576
The Style Guide says to omit the explicit return
Avoid return where not required.
# bad
def some_method(some_arr)
return some_arr.size
end
# good
def some_method(some_arr)
some_arr.size
end
Upvotes: 2
Reputation: 26483
Pros for return a + b
:
Cons:
Upvotes: 0
Reputation: 12265
It all depends on the context. Usually, it is not necessary to put it explicitly: rubyists knows that the last expression is the returned one. However, on some rare occasions, the last expression is not easy to grasp, as in an interation or some obscure structure, so it might be good to put it. But usually, no not necessary.
EDIT:
And obviously, when you're trying to return an expression that is not the last of your method, you have to use return. As you would do with lazy-loaded accessors
Upvotes: 0