ruby 从散列数组中收集值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18899868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:10:46  来源:igfitidea点击:

Collect values from an array of hashes

rubyarrayshashcollect

提问by Kert

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 :priceas an array like [1,2,3]?

有没有一种有效的方法来获取:price像这样的数组的值[1,2,3]

回答by Zabba

First, if you are using ruby < 1.9:

首先,如果您使用 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]}