Techioz Blog

Ruby でハッシュの配列をマッピングするよりエレガントな方法

概要

ハッシュの配列があります: 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)