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

Return from inside a method, but outside a loop

Try running this code.

When method1 is run, the hash is returned twice, meaning the hash is returned and printed as intended by the 'puts method1().inspect' command.

When method2 is run, and the loop is exited second time-around, by typing "no" or "n", a bunch of seemingly random numbers are printed, instead of a lovely hash. Why is this????

def method1

    loop do
        print "Item name: "
        item_name = gets.chomp

        print "How much? "
        quantity = gets.chomp.to_i

        hash = {"Item"=> item_name, "quantity"=> quantity}
        puts hash.inspect

        return hash
    end

end

puts method1().inspect


def method2

    loop do
        print "Item name: "
        item_name = gets.chomp

        print "How much? "
        quantity = gets.chomp.to_i

        hash = {"Item"=> item_name, "quantity"=> quantity}
        puts hash.inspect

        print "Add another item? "
        answer = gets.chomp.downcase
        break if (answer == "no") || (answer == "n")
    end

    return hash

end

puts method2().inspect

1 Answer

The hash in method2 was declared in the loop, so it drops out of scope before the return. You can declare the hash before entering the loop to fix that.

That's awesome, thanks. I don't understand why it drops out of scope, but maybe I'll just have to accept it!

PS I simply added

hash = {}

before the loop and it solved the problem.

It drops out of scope because it is defined inside the block. Anything declared in block will dissapear once the loop is over OR it can pass things to already existing variable and change them.

You define hash, loop over it and then END the loop, THEN You want to return that hash but there is nothing to return because it does not exist anymore, hence the weird numbers when You call return.