循环遍历Ruby中的Array和对象的多维哈希

时间:2015-05-25 08:19:53

标签: ruby-on-rails ruby

实际上是尝试访问多维哈希的值,看起来像这样

displayInternationalCopy

例如,如何使用循环获取每个page_x中的:price?

2 个答案:

答案 0 :(得分:1)

试试这个:

pages = {
 "page_1"=>[
     {:price=>"40 €", :price_per_day=>"40 €", :provider1=>"XX"}, 
     {:price=>"43 €", :price_per_day=>"43 €", :provider1=>"XX"}
   ],
  "page_2"=>[
     {:price=>"40 €", :price_per_day=>"40 €", :provider1=>"XX"}, 
     {:price=>"43 €", :price_per_day=>"43 €", :provider1=>"XX"}
   ]
 }

pages.each do |page, prices_array|
  puts page #=> "page_1", and "page_2" on the next iteration
  prices_array.each do |price|
    puts price[:price]
    puts price[:price_per_day]
    puts price[:provider1]
  end
end

each do |page, prices_array|中,pagekeyprices_array是每次迭代时哈希的value。由于value是一个数组,我们将不得不再做一个each来迭代数组的值。

答案 1 :(得分:0)

如果您只需要价格,可以这样做:

   hash.values.flatten.map{ |e| e[:price] }
    => ["40 €", "43 €", "40 €", "43 €"]