0

Given the following code (where I display some statistics about a number of bookings):

statistics = [["Germany", "EUR"], 23], [["Germany", "USD"], 42], [["Spain", "EUR"], 17]

statistics.each do |country_and_currency, number_of_bookings|
  country, currency = country_and_currency # <-- Ugly.

  puts "There are #{number_of_bookings} in #{currency} in #{country}"
end

The country_and_currency part is quite ugly. I tried ... do |*(country, currency), number_of_bookings|, but this did not work.

Is there an elegant way to process this nested array without using the country_and_currency variable?

2 Answers 2

5

Yes, it's possible:

statistics = [
               [["Germany", "EUR"], 23], 
               [["Germany", "USD"], 42], 
               [["Spain", "EUR"], 17]
             ]

statistics.each do |(country, currency), number_of_bookings|
  puts "There are #{number_of_bookings} in #{currency} in #{country}"
end

Output

There are 23 in EUR in Germany
There are 42 in USD in Germany
There are 17 in EUR in Spain
Sign up to request clarification or add additional context in comments.

Comments

2
statistics.each do |(country, currency), number_of_bookings|
  puts "There are #{number_of_bookings} in #{currency} in #{country}"
end

Comments

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.