从一系列哈希中获取数据

时间:2014-05-28 13:18:30

标签: ruby ruby-on-rails-4

给出以下哈希数组:

[{name: "joe", age: 21}, {name: "mary", age: 32}, {name: "mark", age: 25}]

如何获取返回的名称数组,如下所示:

["joe","mary","mark"]

3 个答案:

答案 0 :(得分:4)

使用#map

arr = [{name: "joe", age: 21}, {name: "mary", age: 32}, {name: "mark", age: 25}]
arr.map { |x| x[:name] }
# => ["joe", "mary", "mark"] 

答案 1 :(得分:2)

只需使用Array#collect方法

即可
ary_of_hash = [{name: "joe", age: 21}, {name: "mary", age: 32}, {name: "mark", age: 25}]
ary_of_hash.collect { |hash| hash[:name] }

答案 2 :(得分:-3)

我认为地图解决了这个问题。

[{name: "joe", age: 21}, {name: "mary", age: 32}, {name: "mark", age: 25}].map(function(node){return node.name});

// returns ["joe", "mary", "mark"]
.map()

Reference and fallback