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?

···

--
Posted via http://www.ruby-forum.com/.

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(tm) 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 <james.schoonmaker@gmail.com> wrote:

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?
--
Posted via http://www.ruby-forum.com/\.

Patrick Doyle 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(tm) 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"

···

--
Posted via http://www.ruby-forum.com/\.

Lloyd Linklater wrote:

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")

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

Does the same without return.

···

--
Jabber: sepp2k@jabber.org
ICQ: 205544826

Sebastian Hungerecker wrote:

Lloyd Linklater 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 Linklater wrote:

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

--
Posted via http://www.ruby-forum.com/\.