Good practice for explicitly returning function values?

Would you prefer this:

def add(a, b)
  puts "ADDING #{a} + #{b}"
  return a + b
end

above this?

def add(a, b)
  puts "ADDING #{a} + #{b}"
  a + b
end
+3
source share
5 answers

It The Ruby Way ™ to not include an operator return, if not required.

I am sure there are better examples, but simple here.

def divide a, b
    return false if b == 0
    a/b
end

It is worth noting that Ruby provides options for optionally ignoring a lot of syntax. ()are optional if you have not invested them. {}may also be omitted in many cases.

func(5, 5, {:hello => 'world'})
# is the same as
func 5, 5, hello: 'world'

You will recognize many more shortcuts when you go.

+4
source

Style Guide says explicit return

Avoid returning to where it is not required.

# bad
def some_method(some_arr)
  return some_arr.size
end

# good
def some_method(some_arr)
  some_arr.size
end
+2
source

. : , . , - , . .

EDIT:

, , , , return.

0

return a + b:

:

0

All Articles