Newbie question- Return method

I’m trying to teach myself the basics of Ruby (based on the guide at
http://pine.fm/LearnToProgram), and I ran across the Return method. I’m
not clear on what it does and how it works, though, and all of the
searches I made for it didn’t address the method itself.

Any help?

The word “return” is a reserved word in ruby, just like the words
“def”, “if”, “while”, etc…

“return” is used in a method to exit the method and to return the
given value to the caller. In principal, you could write

def compute_square(x)
return x*x
end

…although The Ruby Way™ would be to simply write:

def compute_square(x)
x*x
end

since, by the definition of the language, the return value of a method
is (99.99% of the time) the last expression computed in the method.

–wpd

On Wed, Oct 1, 2008 at 8:33 AM, James Schoonmaker

Lloyd L. wrote:

def myMethod s
 d = “foo”
 s.upcase!
 return d
end

p myMethod(“hiya”)

Yes, but:
def myMethod s
d = “foo”
s.upcase!
d
end
p myMethod(“hiya”)

Does the same without return.

Patrick D. wrote:

The word “return” is a reserved word in ruby, just like the words
“def”, “if”, “while”, etc…

“return” is used in a method to exit the method and to return the
given value to the caller. In principal, you could write

def compute_square(x)
return x*x
end

…although The Ruby Way™ would be to simply write:

def compute_square(x)
x*x
end

since, by the definition of the language, the return value of a method
is (99.99% of the time) the last expression computed in the method.

You can use it to pick what you want returned if it is not the last
thing in the method.

e.g.

def myMethod s
d = ‘foo’
s.upcase!
end

p myMethod(“hiya”)

=> “HIYA”

However

def myMethod s
d = “foo”
s.upcase!
return d
end

p myMethod(“hiya”)

=> “foo”

Sebastian H. wrote:

Lloyd L. wrote:

def myMethod s
 d = “foo”
 s.upcase!
 return d
end

p myMethod(“hiya”)

Yes, but:
def myMethod s
d = “foo”
s.upcase!
d
end
p myMethod(“hiya”)

Does the same without return.

While that is true, I wanted to keep it to the point for this thread. I
did refer to it when I said,

Lloyd L. wrote:

You can use it to pick what you want returned if it is not the last
thing in the method.