Home Sum all values from JSON response
Reply: 2

Sum all values from JSON response

almo Published in 2017-11-08 17:09:56Z

I have a JSON response that looks like this:

   "km"   =>"32.381",
   "tarifa"   =>25.6
   "km"   =>"23423",
   "tarifa"   =>235.6

I want to get the sum of all tarifas. I know that I need to use map for this but am still confused on how to do it.

Ilya Reply to 2017-11-08 17:15:07Z

Just use Array#sum:

array.sum { |e| e['tarifa'] }
#=> 261.2
Jacques Bounliphone
Jacques Bounliphone Reply to 2017-11-08 17:24:02Z

Use reduce to operate through the elements of a list:

arr.map { |elt| elt["tarifa"] }.reduce(:+) (readable way)

arr.reduce(0) { |acc, elt| acc + elt["tarifa"] } (former reduce way, without array regeneration)

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.389252 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO