我如何在哈希数组中映射get操作?

问题描述 投票:0回答:1

我正在使用Rails5。我有一个哈希数组,每个哈希都有一个“ id”键。我想获得一个仅包含每个哈希ID值的对应数组。我尝试过此

[14] pry(main)> arr_of_hashes = [{:id => "abc"}, {:id => "cdef"}, {:id => "123"}]
=> [{:id=>"abc"}, {:id=>"cdef"}, {:id=>"123"}]
[15] pry(main)> arr_of_hashes.map(&:id)
NoMethodError: undefined method `id' for {:id=>"abc"}:Hash

但是您可以看到,它在抱怨“地图”。什么是正确的方法?

arrays hash ruby-on-rails-5 iteration
1个回答
0
投票

您接近。不要踢自己:

arr_of_hashes = [{:id => "abc"}, {:id => "cdef"}, {:id => "123"}]
ids = arr_of_hashes.map { |hash| hash[:id] } 
puts ids # ["abc", "cdef", "123"]

您使用map的方式应该是一种方法:map(&:method)

© www.soinside.com 2019 - 2024. All rights reserved.