处理嵌套数组

ibl*_*lue 0 ruby

给出以下代码(我显示一些有关预订的统计信息):

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
Run Code Online (Sandbox Code Playgroud)

country_and_currency部分非常难看.我试过了... do |*(country, currency), number_of_bookings|,但这没用.

有没有一种优雅的方法来处理这个嵌套数组而不使用country_and_currency变量?

Aru*_*hit 5

是的,这是可能的:

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
Run Code Online (Sandbox Code Playgroud)

产量

There are 23 in EUR in Germany
There are 42 in USD in Germany
There are 17 in EUR in Spain
Run Code Online (Sandbox Code Playgroud)