0

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?

3
  • 2
    It might help to know exactly what you want to do with the prices. In the first answer below you can see how to use a nested loop to access all of the prices within each page, however if you're doing any computations or collations on them, there may be a better answer we could provide ... It's always best to explain in detail what you're trying to achieve rather than just asking what you think you need. Commented May 25, 2015 at 8:33
  • I agree with Jon, if you provide an explanation stating your problem and what you're exactly trying to do then you can receive much better answer than what I presented below. Commented May 25, 2015 at 8:35
  • No not for computation work, Im just using capybara to crawl some datas from a website for statistics purpose. So the whole purpose of my code is to crawl and add it to a CSV file( thats were I got stuck with this multidimensional hash) Commented May 25, 2015 at 8:37

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

2 Comments

I'll stick with surya's solution, beacause I need all informations from the hash. Even though thank you for the answer
I agree with you, if you need all information, surya's solution is better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.