Understanding the return method

F

Fily Salas

Hi,

As always, I'm asking simple questions sorry.

Please help me to understand the "return" method because I dont see
where or how to use it.
Here I'm using the return method but the thing is that if remove it, it
also works, so I was wondering why would you use it if by defaul all
methods return a value?

def multiply(val1, val2 )
result = val1 * val2
return result
end

value = multiply( 10, 20 )
puts value

Can some one show me the main purpose of using the return method?

Again I'm currently trying to understand the basics, so please be
patient : )

Thanks
 
I

Iñaki Baz Castillo

2011/4/17 Fily Salas said:
def multiply(val1, val2 )
=C2=A0 =C2=A0 result =3D val1 * val2
=C2=A0 =C2=A0 return result
end

A ruby method always returns the last object or expression it calls
internally. But if there is a return(something) within the method then
such object "something" is returned by the method. Note also that
"return" is the same as "return nil".

In your above method, it would be the same as:

def multiply(val1, val2 )
result =3D val1 * val2
end


or also:


def multiply(val1, val2 )
result =3D val1 * val2
result
end


The advantage of using "return" is that you terminate the method when
you want without running the remaining code defined in the method.


--=20
I=C3=B1aki Baz Castillo
<[email protected]>
 
V

Vincent Manis

Hi,
=20
As always, I'm asking simple questions sorry.
Don't be sorry, questions need answers :).=20
Please help me to understand the "return" method because I dont see
where or how to use it.
Here I'm using the return method but the thing is that if remove it, = it
also works, so I was wondering why would you use it if by defaul all
methods return a value?
=20
def multiply(val1, val2 )
result =3D val1 * val2
return result
end

The right way to understand return is thst it's a control operation, it =
tells Ruby to exit from the procedure RIGHT NOW, with an optional return =
value. So you (almost) never need it as the last step in a function (the =
exception is given below), but you use it if you have the result you =
need, and don't want to execute the current procedure any more.=20

irb(main):001:0> def how_many_sum_to(n)
irb(main):002:1> sum =3D 0
irb(main):003:1> i =3D 1
irb(main):004:1> loop do=20
irb(main):005:2* sum +=3D i=20
irb(main):006:2> return i if sum > n=20
irb(main):007:2> i +=3D 1
irb(main):008:2> end
irb(main):009:1> end
=3D> nil
irb(main):010:0> how_many_sum_to(12)
=3D> 5

The (poorly-named) procedure keeps adding integers until it gets a value =
greater than n, and returns the value that put the sum over the top. =
(You can get the same answer without a loop if you do some algebra, but =
that's not relevant here.) I used a loop here rather than a while to =
demonstrate that in this example the return acts like a break, exiting =
the loop and the containing procedure.=20

irb(main):028:0> def print_square_root(x)=20
irb(main):029:1> if x > 0
irb(main):030:2> print("the square root of %f is %f\n"%[x, =
Math.sqrt(x)])
irb(main):031:2> return
irb(main):032:2> end
irb(main):033:1> print("sorry, I don't know about complex numbers =
yet\n")
irb(main):034:1> end
=3D> nil
irb(main):035:0> print_square_root(4)
the square root of 4.000000 is 2.000000
=3D> nil
irb(main):036:0> print_square_root(-4)
sorry, I don't know about complex numbers yet
=3D> nil

Here we used a return to exit from a procedure early, even without a =
loop.=20

Both of these procedures could be refactored to eliminate the need for =
return. In many (most?) cases, code reads more clearly without a return =
than with. The exception comes when you have perhaps several levels of =
nested loops, or some rescues, or the like. So I tend to see the =
presence of a return as an invitation to refactor, but there are =
certainly many cases where the version with return is the clearest.=20

There's one exception to the rule that a return as the last statement of =
a procedure is unnecessary. If you want to return several values, you =
need a return, because a comma-separated list of expressions isn't =
itself an expression.=20

irb(main):037:0> def return_needed(x)
irb(main):038:1> x+1, x-1
irb(main):039:1> end
SyntaxError: (irb):38: syntax error, unexpected ',', expecting =
keyword_end
x+1, x-1
^
from /Users/vmanis/local/bin/irb:12:in `<main>'
irb(main):040:0> def return_needed(x)
irb(main):041:1> return x+1, x-1
irb(main):042:1> end
=3D> nil
irb(main):043:0> return_needed(4)
=3D> [5, 3]

Of course, since returning multiple values returns an array, you can =
again eliminate the need for return by explicitly returning an array.=20

irb(main):044:0> def return_needed(x)
irb(main):045:1> [x+1, x-1]
irb(main):046:1> end

Hope this helps. -- vincent
 
J

jake kaiden

hey fily -

i'm not the best person to answer this question (as i'm really
something of a newb myself,) but i'll get you started...

every method in ruby returns a value (even if it is nil, thus all the
=>nil's in irb.) by default, the value that a method returns is the
LAST statement evaluated - which is something to be aware of.

note that for the example you have shown this works just as well:

def multiply(val1, val2 )
val1 * val2
end

value = multiply( 10, 20 )
puts value

#=> 200

while there are really times when you want to use 'return,' (which
surely someone else can better explain,) generally speaking, the last
statement evaluated in your method is what is returned.

-j
 
J

jake kaiden

hi fily -

while i was answering your post, vincent answered it much better than
i ever could have.

the one thing that i would point out, is that it is important to
remember that by default ruby returns the LAST statement evaluated (this
can bite you in the arse if you forget!)

the example you gave could also be written like this (without
'return'):

def multiply(val1, val2 )
val1 * val2
end

value = multiply( 10, 20 )
puts value

#=>200

-j
 
F

Fily Salas

Beautiful, got it, thank you all very much for your help, it feels good
when things start to make sense and the return operator now make sense
to me.

Thanks a lot!
 
7

7stud --

jake kaiden wrote in post #993280:
hi fily -

while i was answering your post, i=C3=B1aki and vincent answered it m= uch
better than i ever could have. ignore the deleted greyness, and rock
on...

Hi jake,

There's no need to delete your post when someone answers ahead of =

you-even if you give the exact same advice. That sort of thing happens =

all the time. And sometimes hearing an explanation from a fellow =

beginner will make more sense than an answer from an expert.

-- =

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

Vincent Manis

jake kaiden wrote in post #993280:
=20
There's no need to delete your post when someone answers ahead of=20
you-even if you give the exact same advice. That sort of thing = happens=20
all the time. And sometimes hearing an explanation from a fellow=20
beginner will make more sense than an answer from an expert.

I couldn't agree more. I appreciate the compliment about my answer, but =
sometimes even saying the same thing in different words can help a =
person. I'd rather see redundant answers than insufficient ones!

In any case, Jake's answer was admirably concise, whereas mine was =
anything *BUT* concise. So not just Fily but also anyone else who was =
puzzled about return got both the brief answer *AND* the long-winded =
one.=20

-- vincent=
 
I

Iñaki Baz Castillo

2011/4/17 7stud -- said:
There's no need to delete your post when someone answers ahead of
you-even if you give the exact same advice. =C2=A0That sort of thing happ= ens
all the time. =C2=A0 And sometimes hearing an explanation from a fellow
beginner will make more sense than an answer from an expert.

Sure. In fact, sometimes is really interesting (at least for me) to
get the opinnion of people coming from other languages in which same
or similar concepts apply but in a different way.

--=20
I=C3=B1aki Baz Castillo
<[email protected]>
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top