Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Rahul Nayak
Rahul Nayak
1,221 Points

What is the significance of return statement?

def add(a, b)

puts "Adding #{a} and #{b}:"

return a + b

end

add (2,3)

When it is tried to invoke add function with 2,3 parameters, it would not give me the result but only "Adding 2 and 3:". I don't understand why it does not return the sum of a+b and what is the real significance of using a return statement if I can simply use puts or print? Basically I did not understand return statement :(

2 Answers

Justin Horner
STAFF
Justin Horner
Treehouse Guest Teacher

Hello Rahul,

The point of the return statement is to return a value to the caller of the function. In the code you have provided, the sum of a and b are being returned but not used by your calling code. Here's an example of how you could use the return value.

def add(a, b)
    puts "Adding #{a} and #{b}:"
    return a + b
end

sum = add (2,3)
puts "Now I have the sum of 2 and 3 (#{sum}) available outside the method"

I hope this helps.

Rahul Nayak
Rahul Nayak
1,221 Points

I will quote your words "the sum of a and b are being returned but not used by your calling code.". If I understood this correctly, it means that when I call the function, the sum is calculated but not displayed because I have not asked for it. Right?

Justin Horner
Justin Horner
Treehouse Guest Teacher

Yes, you're right. The function is calculating the sum of a and b but you were not storing the returned value in a variable. In the code I shared you'll notice I stored the value returned from the function in a variable called sum.

Rahul Nayak
Rahul Nayak
1,221 Points

got it now !! Thanks a lot Justin Horner .

Rahul Nayak
Rahul Nayak
1,221 Points

got it now !! Thanks a lot Justin Horner .