我正在使用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
但是您可以看到,它在抱怨“地图”。什么是正确的方法?
您接近。不要踢自己:
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)