在RUBY中使用哈希的正确方法

时间:2013-12-03 03:56:06

标签: ruby hash

我有一个菜单的哈希,我需要迭代值。每个项目都有两种尺寸SMLLRG。我们假设这是我的hash

fullMenu = [{:item => "pasta",   :sml => 550, :lrg => 975}, 
            {:item => "chicken", :sml => 725, :lrg => 1150},
            {:item => "shrimp",  :sml => 975, :lrg => 1350}]

现在我想做的是遍历每个item / size - price以构建菜单。

fullMenu.each do |item, p_sml, p_lrg|
    puts "#{item} Small: $#{p_sml} -or- Large: $#{p_lrg}"
end

我的输出是:

{:item=>"pasta", :sml=>550, :lrg=>975} Small: $ -or- Large: $
{:item=>"chicken", :sml=>725, :lrg=>1150} Small: $ -or- Large: $
{:item=>"shrimp", :sml=>975, :lrg=>1350} Small: $ -or- Large: $

不完全是我想要的。因为没有输出。最后,我实际上希望puts成为puts "#{item} Small: $#{"%.2f" % p_sml / 100} -or- Large: $#{"%.2f" % p_lrg / 100}"以正确显示价格。我在这里错过了什么?这被称为多维hasharray

2 个答案:

答案 0 :(得分:2)

fullMenu = [{:item => "pasta",   :sml => 550, :lrg => 975}, 
            {:item => "chicken", :sml => 725, :lrg => 1150},
            {:item => "shrimp",  :sml => 975, :lrg => 1350}]

fullMenu.each { |h|
  puts "%s Small: %.2f -or- Large: %.2f" % [h[:item], h[:sml]/100.0, h[:lrg]/100.0]
}

输出:

pasta Small: 5.50 -or- Large: 9.75
chicken Small: 7.25 -or- Large: 11.50
shrimp Small: 9.75 -or- Large: 13.50

答案 1 :(得分:0)

您可以对哈希的值运行map

2.0.0p247 :010 > fullMenu = [{:item => "pasta",   :sml => 550, :lrg => 975}, 
2.0.0p247 :011 >                 {:item => "chicken", :sml => 725, :lrg => 1150},
2.0.0p247 :012 >                 {:item => "shrimp",  :sml => 975, :lrg => 1350}]
 => [{:item=>"pasta", :sml=>550, :lrg=>975}, {:item=>"chicken", :sml=>725, :lrg=>1150}, {:item=>"shrimp", :sml=>975, :lrg=>1350}] 
2.0.0p247 :013 > fullMenu.map(&:value)
 => [{:item=>"pasta", :sml=>550, :lrg=>975}, {:item=>"chicken", :sml=>725, :lrg=>1150}, {:item=>"shrimp", :sml=>975, :lrg=>1350}] 

2.0.0p247 :014 > fullMenu.map(&:values)
 => [["pasta", 550, 975], ["chicken", 725, 1150], ["shrimp", 975, 1350]] 

然后,您的代码将起作用:

fullMenu.each do |item, p_sml, p_lrg|
  puts "#{item} Small: $#{p_sml} -or- Large: $#{p_lrg}"
end

这被称为多维哈希或数组吗?

这将是一系列哈希。如果你愿意,你可以做一个数组数组,但我认为这种方式有效。

编辑 - 所有这些都说,更好的方法就是@falsetru所拥有的。