如何检索与哈希数组中存在的哈希键相关的值

时间:2022-11-30 12:42:12

I am using Ruby on Rails 3.2.2 and I would like to retrieve values related to a hash key present in a Array of Hashes. That is, I have the following Array of Hashes:

我正在使用Ruby on Rails 3.2.2,我想检索与哈希数组中存在的哈希键相关的值。也就是说,我有以下哈希数组:

[
  {
    :key1 => value_a_1,
    :key2 => value_a_2
  },
  {
    :key1 => value_b_1,
    :key2 => value_b_2
  },
  {
    :key1 => value_c_1,
    :key2 => value_c_2
  }
]

I would like to "retrieve" / "build" the following:

我想“检索”/“构建”以下内容:

[ value_a_1, value_b_1, value_c_1 ]

How can I make that the proper way?

我怎样才能以正确的方式做到这一点?

1 个解决方案

#1


2  

If a is the array:

如果a是数组:

a.map { |i| i[:key1] }

#1


2  

If a is the array:

如果a是数组:

a.map { |i| i[:key1] }