我有一个哈希数组:
hashes = [{field: 'one'}, {field: 'two'}]
我想从中获取字段列表:
['one', 'two']
hashes.map(&:field)
显然不起作用,而且 hashes.map { |hash| hash[field] }
对我来说感觉有点笨拙。
还有更优雅的方式吗?
编辑:我应该澄清一下,我只想要我的回复中“字段”的值。
所以,
hashes = [{field: 'one', another: 'three'}, {field: 'two'}].do_the_thing
应该是 ['one', 'two']
也许像下面这样的东西会更顺眼:
hashes = [{field: 'one', another: 'three'}, {field: 'two'}]
fields = lambda { |hash| hash[:field] }
hashes.collect(&fields)
不确定这是否更好,但也许读起来更清楚一点:
hashes.map { |hash| hash.values }.flatten
如果您使用 Rails,ActiveSupport 为此定义 Enumerable#pluck:
hashes = [{field: 'one'}, {field: 'two'}]
hashes.pluck(:field)
# => ["one", "two"]