LoginSignup
52
23

More than 5 years have passed since last update.

Ruby 2.7 で追加される `Enumerable#tally` というメソッドについて

Posted at

Ruby 2.7 で Enumerable#tally というメソッドが追加されます。

あまり聞き慣れない単語のメソッドですが、これは『同じ要素の数を Hash で返す』というメソッドになります。

pp [1, 1, 2, 2, 2, 3, 3, 4].tally
# => {1=>2, 2=>3, 3=>2, 4=>1}

pp ["homu", "homu", "mami", "mado", "mado", "mado"].tally
# => {"homu"=>2, "mami"=>1, "mado"=>3}

『要素をキー』として『要素の数を値』とする Hash を返します。
配列の要素の数を数えたいことは稀によくあるので、そういう場合に一発で取得できるのは便利そうですね。
また、機能としては Enumerable#group_by と似ていますが、 #tally はブロックを受け取らないことに注意してください。
ちなみに tally という単語は、日本語で数を数える時に使う の字と同じような意味合いがあるらしいです。

52
23
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
52
23