1

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?

Thermatix
  • 2,757
  • 21
  • 51

2 Answers2

4

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!

Paweł Dawczak
  • 9,519
  • 2
  • 24
  • 37
1

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

Community
  • 1
  • 1
Abdul Baig
  • 3,683
  • 3
  • 21
  • 48
  • I will tick this as correct simply because It possess both ways (even if the only difference is that one is an alias of the other) and has a source link for information, the other answer is still however correct. – Thermatix Apr 28 '15 at 13:56