简体   繁体   中英

aggregate values from specific key in an array of hashes

I'm trying to build an array of values that come from an array of hashes, at the moment my code looks like this:

ids = array_of_hashes.inject([]) do |result,instance|
    result << instance[:id]
    result
end

I just want to know if there's a more efficient way to do it?

You could change it to look like:

ids = hash.map { |instance| instance[:id] }

Not necessarily more efficient, but easier to read and maintain!

Good luck!

There are two easy ways for it:

 1. ids = hash.collect{|h| h[:id]} 
 2. ids = hash.map{|h| h[:id]}

Now you would ask what is the difference in both? for explanation see this accepted answer

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