一种更优雅的方式来映射ruby中的哈希数组

时间:2014-11-12 23:32:24

标签: ruby hash

我有一系列哈希: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']

3 个答案:

答案 0 :(得分:3)

或许类似以下内容会更令人赏心悦目:

hashes = [{field: 'one', another: 'three'}, {field: 'two'}]
fields = lambda { |hash| hash[:field] }

hashes.collect(&fields)

答案 1 :(得分:1)

查看flat_map

hashes = [{field: 'one'}, {field: 'two'}]
hashes.flat_map(&:values) # => ["one", "two"]

答案 2 :(得分:1)

不确定这是否更好,但也许它读得更清楚:

hashes.map { |hash| hash.values }.flatten

相关问题