Collect values from an array of hashes

Kert picture Kert · Sep 19, 2013 · Viewed 53.7k times · Source

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

Answer

Zabba picture Zabba · Sep 19, 2013

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