给出以下哈希数组:
[{name: "joe", age: 21}, {name: "mary", age: 32}, {name: "mark", age: 25}]
如何获取返回的名称数组,如下所示:
["joe","mary","mark"]
答案 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()
的