![見出し画像](https://assets.st-note.com/production/uploads/images/90532916/rectangle_large_type_2_6f881a679dee8d8f04c1758f961de9ca.png?width=1200)
Enumerable#tally
結論
Rubyでプログラムを書く時に便利なメソッドを見つけたので共有です。
Enumerable#tally Enumerable(配列やハッシュ)に含まれる要素を数えてハッシュを返すメソッドです。group_byからのcountのような記述を1メソッドで表現できます。
具体例
The Great Gatsbyのwikipediaのあらすじに使用されているアルファベットの数を数えてみます。(The Great Gatsbyは良い小説ですよね( ✌︎'ω')✌︎)
# あらすじを変数に代入
the_greatt_gatsby_synopsis = <<"TEXT"
The Great Gatsby is a 1925 novel by American writer F. Scott Fitzgerald. Set in the Jazz Age on Long Island, near New York City, the novel depicts first-person narrator Nick Carraway's interactions with mysterious millionaire Jay Gatsby and Gatsby's obsession to reunite with his former lover, Daisy Buchanan.
TEXT
# 改行文字削除、スペース削除、小文字に統一など前処理をする
pretreated_the_greatt_gatsby_synopsis = the_greatt_gatsby_synopsis.chomp!.gsub(" ", "").downcase.split(//)
pp pretreated_the_greatt_gatsby_synopsis
>>
["t",
"h",
"e",...
"a",
"n",
"."]
pp pretreated_the_greatt_gatsby_synopsis.tally
>>
{"t"=>23,
"h"=>7,
"e"=>23,...
"-"=>1,
"'"=>2,
"u"=>3}
# 文字ごとに出現回数を取得できる
せっかくなのでグラフにしてみました。
一番出現回数が多い文字は「a」でした!意外と出現回数にブレがありますね。
![](https://assets.st-note.com/img/1667637360259-VAUIx0HJad.png)
まとめ
便利メソッドは知っているだけで、実装がシンプルになるので良いですよね。こんな便利メソッド知ってるぜ!というかたはコメントくださいー!
参考資料
https://thoughtbot.com/blog/histogram-distribution-in-ruby-is-double-tally
この記事が気に入ったらサポートをしてみませんか?