繁体   English   中英

哈希输出格式存在问题

[英]Issues with the output format of 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 } 

但是我只是不知道该如何改变。 我已经花了数小时试图弄清楚它是如何工作的,因此,如果有人可以给我提示或帮助我,我将不胜感激! (同样,我对模糊的标题表示歉意,对如何形容它并不太了解...)

是的,你是对的。 问题是这条线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

您将项目名称及其成本存储在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

让我知道是否有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM