简体   繁体   中英

Loop through multidimensional hash of Array and objects in Ruby

Actually trying to access the values of multidimensional hash, which looks like this

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

For example how can I get the :price inside each page_x using a loop?

Try this:

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

Here in each do |page, prices_array| , page is the key and prices_array is the value of hash on each iteration. Since value is an array, we will have to do another each for iterating values of the array.

If you just need the price, you can do like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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