Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4612

How do I map an array of hashes?

$
0
0

I have an array of hashes:

arr = [ {:a => 1, :b => 2}, {:a => 3, :b => 4} ]

What I want to achieve is:

arr.map{|x| x[:a]}.reduce(:+)

but I think it's a bit ugly, or at least not that elegant as:

arr.map(&:a).reduce(:+)

The later one is wrong because there is no method called a in the hashes.

Are there any better ways to write map{|x| x[:a]}?


Viewing all articles
Browse latest Browse all 4612

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>