【发布时间】:2015-01-09 17:44:10
【问题描述】:
尝试运行此代码。
当 method1 运行时,哈希会返回两次,这意味着哈希会按照“puts method1().inspect”命令的预期返回和打印。
当方法 2 运行时,循环第二次退出,通过键入“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
【问题讨论】:
-
hash不是你想的那样;循环内的hash仅对该块可见。如果你使用的变量名还不是方法,你会得到一个非常不同的结果:) -
也不是你问题的答案,只是一个说明。您的
hash变量将只保存最后一个结果,因为您在每个循环中使用hash =覆盖它。看Hash#merge