Ruby returning from inside a method but outside a loop -
try running code.
when method1 run, hash returned twice, meaning hash returned , printed intended 'puts method1().inspect' command.
when method2 run, , loop exited sec time-around, typing "no" or "n", bunch of seemingly random numbers printed, instead of lovely hash. why this????
def method1 loop print "item name: " item_name = gets.chomp print "how much? " quantity = gets.chomp.to_i hash = {"item"=> item_name, "quantity"=> quantity} puts hash.inspect homecoming hash end end puts method1().inspect def method2 loop 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 item? " reply = gets.chomp.downcase break if (answer == "no") || (answer == "n") end homecoming hash end puts method2().inspect
you've accidentally discovered object#hash
method. don't declare hash
outside loop, not in scope homecoming @ end. instead, returns hash()
method value, big negative number instance.
fire irb, , type hash, you'll see same thing:
(505)⚡️ irb 2.1.2 :001 > hash => -603961634927157790
so instead, seek this:
def method2 hash = {} loop # ...
also aware aren't adding hash, you're re-creating every time.
ruby loops methods return
No comments:
Post a Comment