Newbie question- Return method

  • Thread starter James Schoonmaker
  • Start date
J

James Schoonmaker

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?
 
P

Patrick Doyle

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
 
L

Lloyd Linklater

Patrick said:
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"
 
S

Sebastian Hungerecker

Lloyd said:
def myMethod s
=C2=A0 d =3D 'foo'
=C2=A0 s.upcase!
end

p myMethod("hiya")

=3D> =C2=A0"HIYA"

However

def myMethod s
=C2=A0 d =3D "foo"
=C2=A0 s.upcase!
=C2=A0 return d
end

p myMethod("hiya")

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

Does the same without return.

=2D-=20
Jabber: (e-mail address removed)
ICQ: 205544826
 
L

Lloyd Linklater

Sebastian said:
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,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top