'return' in a method


#1

Just doing unit 5, point 7 (Ruby course) which talks about return.
In the following code, why is return so important, is the result is the same if you remove it?

def carre(n)
  return n ** 3
end

sortie=carre(8)
sortie*=2

puts sortie

In both cases, it returns 1024.


#2

Please format your post as I have done (select entire code block; press Ctrl+Shift+C) from next time. Thanks! :smile:

In Ruby methods, if you skip the return statement, the value of the last statement inside the method is returned. So, while your current method doesn't make a difference in presence/absence of return, the following will:

def carre(n)
  return n ** 3
  a = 5
end

sortie = carre(8)
sortie *= 2

puts sortie

Run it here and see if you can understand the point I am trying to make.


#3

Formatted! :smiley:

Many thanks for your help! I got`indent preformatted text by 4 spac it now.