在这段代码中:
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等价物.
解决方法
如果你不介意猴子修补,你可以自己去采摘:
arr = [{ id: 1,body: 'foobar' }] class Array def pluck(key) map { |h| h[key] } end end arr.pluck(:id) => [1,3] arr.pluck(:body) => ["foo","bar","foobar"]
而且,它看起来像someone has already generalised this for Enumerables,还有别人for a more general solution.