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]}
Author by
Kert
Updated on July 05, 2022Comments
-
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 almost 11 yearsThe updated syntax for the "hash" is correct, but at that point
data_hash
is a misnomer. The OP should usedata_hashes
ordata_array
, either of which would be better. -
Zabba almost 11 yearsOops, you are right. Corrected.