Collect values from an array of hashes

62,809

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]}
Share:
62,809
Kert
Author by

Kert

Updated on July 05, 2022

Comments

  • Kert
    Kert almost 2 years

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

  • PJP
    PJP almost 11 years
    The updated syntax for the "hash" is correct, but at that point data_hash is a misnomer. The OP should use data_hashes or data_array, either of which would be better.
  • Zabba
    Zabba almost 11 years
    Oops, you are right. Corrected.