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 Ruby Basics (Retired) Ruby Methods Method Arguments

what happen when we return a method

i do not understand the concept of returning. what happens when we return a method? does it send it back to the file so that it is not printed in the console?

2 Answers

rowend rowend
rowend rowend
2,926 Points

When a method returns a value you can use it. Example the gets method returns a string and you can do anything you want with that string....some times you assign that string to variable. Imagine if the add method could return the result of sum you can declare a variable and store the result of that sum. Imagine you have a method that makes a bigger math operation and then you need that value to make other math operation.

Lets say you have a basic product class like so:

class Product
    attr_accessor :description, :price

    def initialize(description, price)
        @description = description
        @price = price
    end 
end

product = Product.new("Skateboard", 10.99)
puts "$#{product.price}"
puts product.description

Now I want add a method that removes a dollar from the price of our product when we initialize it.

class Product
    attr_accessor :description, :price

    def initialize(description, price)
        @description = description
        @price = add_discount(price)
    end 

    def add_discount(price)
        adjusted_price = price - 1
        return adjusted_price
    end

end

product = Product.new("Skateboard", 10.99)
puts "$#{product.price}"
puts product.description

Whats happening here is when we set our @price instance variable, we are running our add discount method and passing it the original price and it is returning the adjusted price back to our @price variable. Thats essentially what return does, it passes a value back to the place where the method was called (in this case @price)

Thats the best way I can think of explaining my understanding of it, in context. I hope that makes sense and isn't a totally useless answer!