Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 217
Kert Avatar asked Sep 19 '13 16:09

Kert


1 Answers

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]} 
like image 84
Zabba Avatar answered Sep 23 '22 12:09

Zabba