Collect values from an array of hashes [closed]

此生再无相见时 提交于 2019-12-03 07:21:06

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/18899868/collect-values-from-an-array-of-hashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!