在 ruby 中映射哈希数组的更优雅的方式

问题描述 投票:0回答:4

我有一个哈希数组:

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']

ruby hash
4个回答
3
投票

也许像下面这样的东西会更顺眼:

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

hashes.collect(&fields)

1
投票

flat_map

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

1
投票

不确定这是否更好,但也许读起来更清楚一点:

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


0
投票

如果您使用 Rails,ActiveSupport 为此定义 Enumerable#pluck

hashes = [{field: 'one'}, {field: 'two'}]
hashes.pluck(:field)
# => ["one", "two"]
© www.soinside.com 2019 - 2024. All rights reserved.