简体   繁体   中英

accessing data from hash within an array

So I have some number of hashes within an array like follows

arr=[
      {a: 1, b:2, c:3},
      {a:3, b:5, c:4},
      {a:6 b:7, c:9}
     ]

I want to derive the sum of numbers from the last hash. I was thinking of something like

  arr.last[each_value.inject(:+)]

it doesn't work however, what is a better way of doing this?

You can use inject(:+) , or if your Ruby version allows you, use sum :

p arr.last.values.sum(&:to_i) # 22
p arr.last.values.inject { |acc, n| acc + n.to_i } # 22

Your code

arr.last[each_value.inject(:+)] # doesn't work 

arr.last is a hash. so you can use Hash#each_value

arr.last.each_value.inject(:+) #=> 22

Other ways Hash#values , Enumerable#sum , Enumerable#reduce

arr.last.values.sum #=> 22
arr.last.sum { |_key, val| val } #=> 22 
arr.last.reduce(0) { |sum, (_key, val)| sum + val } #=> 22 

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