简体   繁体   中英

Collect values from an array of hashes

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] ?

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]}

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)

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