MrPizzaFace
MrPizzaFace

Reputation: 8086

Proper way to work with a hash in RUBY

I have a hash of a menu that I need to iterate over values. Each item has two sizes SML and LRG. Let's assume this is my hash.

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

Now what I would like to do is iterate over each item / size - price to build out the menu.

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

My output is:

{: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: $

Not exactly what I want. As nothing is being output. Lastly I actually want my puts to be puts "#{item} Small: $#{"%.2f" % p_sml / 100} -or- Large: $#{"%.2f" % p_lrg / 100}" To properly display price. What am I missing here? And is this called a multidimensional hash or array?

Upvotes: 0

Views: 40

Answers (2)

falsetru
falsetru

Reputation: 368894

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]
}

output:

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

Upvotes: 2

CDub
CDub

Reputation: 13344

You could run map on the values of the hashes:

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]] 

Then, your code would work:

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

And is this called a multidimensional hash or array?

This would be an array of hashes. If you wanted, you could do an array of arrays, but I think this way works.

EDIT - All this said, the better way to do it is what @falsetru has.

Upvotes: 0

Related Questions