0
我創建了散列的購物清單,其中存儲了與用戶輸入的項目及其相關的成本。如何引用hash.values創建數組
我想添加存儲在這個哈希中的所有值。我最初的計劃是將它們轉換成一個數組,然後從那裏開始。
hash = {}
entry = " "
while entry != "q"
print "Enter your item: "
item = gets.chomp
print "Enter the associated cost: "
cost = gets.chomp.to_f
print "Press any key to continue or 'q' to quit: "
entry = gets.chomp
hash[item] = cost
end
puts "Receipt: "
puts "----------"
hash.each do |k,v|
puts "#{k} costs $#{v}"
end
puts "----------"
puts "subtotal: "
hash.values
我該如何參考由hash.values
製作的新創建的陣列?
我試過array.inject(0){|sum,x| sum + x }
,但它不起作用,因爲它不會識別新創建的數組。
沒錯奏效!謝謝,我會盡快接受它作爲回答 – Vroryn
我的榮幸爵士:) – Ursus