Enumerable#to_hはブロックを受け取れる
Ruby で、hash を map
で 加工したあとに to_h
してハッシュに戻す、みたいなことをする場面はちょくちょくある。
以下は array
内の各要素の数を数えるために map
と to_h
を併用している例。
array = ['りんご', 'みかん', 'りんご', 'りんご', 'なし', 'みかん']
array.group_by(&:itself).map { |k, v| [k, v.count] }.to_h # => {"りんご"=>3, "みかん"=>2, "なし"=>1}
実は、 Enumerable#to_h
はブロックを受け取れるので map
を使わず以下のように書ける。
array.group_by(&:itself).to_h { |k, v| [k, v.count] }
余談
要素の数を数えたい場合、Ruby2.7 からは Enumerable#tally
を使うのが一番よさそう、
array = ['りんご', 'みかん', 'りんご', 'りんご', 'なし', 'みかん']
array.tally # => {"りんご"=>3, "みかん"=>2, "なし"=>1}