Ruby从方法内部返回但在循环外部返回

时间:2014-11-12 18:49:50

标签: ruby loops methods return

尝试运行此代码。

当运行method1时,哈希返回两次,这意味着哈希被返回并按照'puts method1()。inspect'命令打印。

当运行method2,并且循环退出第二次时,通过键入“no”或“n”,打印出一堆看似随机的数字,而不是可爱的哈希。这是为什么????

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

2 个答案:

答案 0 :(得分:2)

您不小心发现了Object#hash方法。您没有在循环外声明hash,因此它不在最后返回的范围内。相反,它返回hash()方法值,这是该实例的一个很大的负数。

启动irb,只需输入hash,你就会看到同样的事情:

(505)⚡️ irb
2.1.2 :001 > hash
 => -603961634927157790 

相反,试试这个:

def method2
    hash = {}
    loop do
        # ...

另请注意,您不会添加哈希值,而是每次都重新创建哈希值。

答案 1 :(得分:0)

method2中,您尝试返回超出范围的内容(hash)。

method1中,您仍然在返回时定义hash的循环内部。在method2中,您不在定义hash的范围内,因此它具有未记录的结果。像这样重新定义method2

def method2
    hash = nil

    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

现在,即使hash最初设置为nil,其范围也包括整个方法,并且将保留该值。