获取数组中每个哈希的键的值

时间:2022-05-25 22:55:46

I have got an array of hashes, for example:

我有一系列哈希,例如:

[{"id" => "1", "name" => "Name 1"},
 {"id" => "2", "name" => "Name 2"}, 
 {"id" => "3", "name" => "Name 3"}]

I would like to get the value of the key "name" for each hash, similar to this:

我想为每个哈希获取密钥“name”的值,类似于:

["Name 1", "Name 2", "Name 3"]

I looked around for quite a while but couldn't find the answer I was looking for.

我环顾了一会儿,却找不到我想要的答案。

1 个解决方案

#1


1  

It's simplest to use Enumerable#map for this purpose:

为此目的使用Enumerable #map是最简单的:

array = [{"id" => "1", "name" => "Name 1"}, {"id" => "2", "name" => "Name 2"}, {"id" => "3", "name" => "Name 3"}]
array.map { |hash| hash['name'] }
# => ["Name 1", "Name 2", "Name 3"]

#1


1  

It's simplest to use Enumerable#map for this purpose:

为此目的使用Enumerable #map是最简单的:

array = [{"id" => "1", "name" => "Name 1"}, {"id" => "2", "name" => "Name 2"}, {"id" => "3", "name" => "Name 3"}]
array.map { |hash| hash['name'] }
# => ["Name 1", "Name 2", "Name 3"]