hash的输出格式问题

时间:2017-02-23 06:22:45

标签: arrays ruby hash

所以我试图创建一个类似于购物清单的程序,用户将该项目及其相关成本放入其中,并将其显示为列表形式。所以我创造了这个:

arr = []
arr2 = []
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

  arr << item
  arr2 << cost
end

h = { arr => arr2 }   

for k,v in h
  puts "#{k} costs #{v}"
end

(代码可能非常低效,但凭借我有限的初学者知识,它是我能做的最好的事情)

所以我的问题是,当我尝试两个以上的项目时,结果会显示如下(假设我使用Banana和Kiwi作为项目,并为其成本添加一个随机数字):

["Banana", "Kiwi"] costs [2.0, 3,0] 
但是,我希望它显示如下:

Banana costs $2.00

Kiwi costs $3.00

我知道可能需要对这一行采取措施:

h = { arr => arr2 } 

但我不知道我能改变什么。我已经花了几个小时试图弄清楚它是如何工作的,所以如果有人能给我一个提示或帮助我,我会很感激! (同样,我对这个模糊的标题表示道歉,对如何形容它并不了解......)

2 个答案:

答案 0 :(得分:3)

是的,你是对的。问题在于此行h = { arr => arr2 }。此行将创建类似h = {["Banana", "Kiwi"] => [2.0, 3,0]}的散列。

1)如果要使用两个数组,可以按如下方式修改代码。

(0...arr.length).each do |ind|
  puts "#{arr[ind]} costs $#{arr2[ind]}"
end

2)更好的是,您可以使用哈希来存储项目及其成本,然后迭代它以显示结果

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

hash.each do |k,v|
  puts "#{k} costs $#{v}"
end

答案 1 :(得分:2)

您将项目名称及其成本存储在2个不同的阵列中。因此,如果只想保留您的存储结构,则需要修改结果显示,如下所示:

arr.each_with_index do |item, i|
  puts "#{item} costs #{arr2[i]}"
end

但更好的方法是将所有数据存储在1个哈希而不是2个数组中。

items = {}
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

  items[item] = cost
end

items.each do |item, cost|
  puts "#{item} costs #{cost}"
end

如果有帮助,请告诉我。

相关问题