ruby – 有一个干净的方法来访问哈希数组中的哈希值吗?
发布时间:2020-12-16 21:50:10 所属栏目:百科 来源:网络整理
导读:在这段代码中: 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: '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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |