简体   繁体   中英

Extract values from an array of hashes

I need to extract values from an array of hashes:

data =
[{:diaria_media=>"103.58908136482939632545931759", 
  :room_night=>"1143",
  :valor_periodo=>"118402.320000"},   
 {:diaria_media=>"307.46792079207920792079207921", 
  :room_night=>"101",
  :valor_periodo=>"31054.260000"},
 {:diaria_media=>"313.000000",
  :room_night=>"9",
  :valor_periodo=>"2817.000000"},
 {:diaria_media=>"0.0",
  :room_night=>"7",
  :valor_periodo=>"0.0"},
 {:diaria_media=>"4.4630434782608695652173913043",
  :room_night=>"414",
  :valor_periodo=>"1847.700000"},
 {:diaria_media=>"150.89382627422828427853553482",
  :room_night=>"1393",
  :valor_periodo=>"210195.100000"}, 
 {:diaria_media=>"221.11425992779783393501805054",
  :room_night=>"554",
  :valor_periodo=>"122497.300000"},
 {:diaria_media=>"36.919200",
  :room_night=>"25",
  :valor_periodo=>"922.980000"},
 {:diaria_media=>"31.967530864197530864197530864",
  :room_night=>"81",
  :valor_periodo=>"2589.370000"},
 {:diaria_media=>"0",
  :room_night=>"0",
  :valor_periodo=>"0.000000"}]

I need to get all the :room night fields and add the values. What is the best way to achieve that?

first: it's not nice to ask for help and to format the question as you did. second: the question has nothing to do with Rails or with Savon. This is a pure Ruby question. The solution seems simple to me. You iterate over your array and summarize the numbers for each key :room_night For example like this:

nights = 0
data.each do |booking|
    nights += booking[:room_night].to_i
end
print "nights=#{nights}\n"

If you go functional it's even more simple:

nights = data.map{|e| e[:room_night].to_i}.reduce(:+)

and done!

As a bonus I put a executable script into Pastbin https://pastebin.com/29nMTYrK

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