Collect values from an array of hashes

RubyArraysHashCollect

Ruby Problem Overview


I have a data structure in the following format:

data_hash = [
    { price: 1, count: 3 },
    { price: 2, count: 3 },
    { price: 3, count: 3 }
  ]

Is there an efficient way to get the values of :price as an array like [1,2,3]?

Ruby Solutions


Solution 1 - Ruby

First, if you are using ruby < 1.9:

array = [
    {:price => 1, :count => 3},
    {:price => 2, :count => 3},
    {:price => 3, :count => 3}
]

Then to get what you need:

array.map{|x| x[:price]}

Solution 2 - Ruby

There is a closed question that redirects here asking about handing map a Symbol to derive a key. This can be done using an Enumerable as a middle-man:

array = [
    {:price => 1, :count => 3},
    {:price => 2, :count => 3},
    {:price => 3, :count => 3}
]

array.each.with_object(:price).map(&:[])

#=> [1, 2, 3] 

Beyond being slightly more verbose and more difficult to understand, it also slower.


Benchmark.bm do |b| 
  b.report { 10000.times { array.map{|x| x[:price] } } }
  b.report { 10000.times { array.each.with_object(:price).map(&:[]) } }
end

#       user     system      total        real
#   0.004816   0.000005   0.004821 (  0.004816)
#   0.015723   0.000606   0.016329 (  0.016334)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKertView Question on Stackoverflow
Solution 1 - RubyZabbaView Answer on Stackoverflow
Solution 2 - RubyadcView Answer on Stackoverflow