[英]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. 我需要获取所有:room night
字段并添加值。 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. 第二:这个问题与Rails或Savon无关。 This is a pure Ruby question. 这是一个纯粹的Ruby问题。 The solution seems simple to me. 解决方案对我来说似乎很简单。 You iterate over your array and summarize the numbers for each key :room_night For example like this: 您遍历数组并总结每个键的数字:room_night例如:
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 另外,我将可执行脚本放入Pastbin https://pastebin.com/29nMTYrK
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.