在此代码中:
arr = [ { id: 1, body: 'foo'}, { id: 2, body: 'bar' }, { id: 3, body: 'foobar' }]
arr.map { |h| h[:id] } # => [1, 2, 3]
是否有一种更清晰的方法可以从这样的哈希数组中获取值?
Underscore.js has pluck,我想知道是否有Ruby等价物。
答案 0 :(得分:23)
如果你不介意修补猴子,你可以自己动手:
arr = [{ id: 1, body: 'foo'}, { id: 2, body: 'bar' }, { id: 3, body: 'foobar' }]
class Array
def pluck(key)
map { |h| h[key] }
end
end
arr.pluck(:id)
=> [1, 2, 3]
arr.pluck(:body)
=> ["foo", "bar", "foobar"]
此外,它看起来像someone has already generalised this for Enumerables,而其他人for a more general solution。
答案 1 :(得分:2)