LoginSignup
0
0

More than 1 year has passed since last update.

rubyの配列で、同じ値の個数を数える

Last updated at Posted at 2022-05-30

group_byを使うやり方

group_byメソッドで、同じ値のグループを作成し、
key value形式で、
mapメソッドの中で集計する
最後にto_hで見やすく出来る

ary = [1, 1, 1, 2, 3, 3]

p ary.group_by(&:itself).map{ |key,value| [key, value.count] }.to_h

=> {1=>3, 2=>1, 3=>2}

to_h抜きだと見にくい
スクリーンショット 2022-05-31 8.55.10.png

参考文献

group_by
こんな感じで、デフォルトではハッシュが作成される。

ary = [1, 1, 1, 2, 3, 3]

p ary.group_by(&:itself)
p ary.group_by(&:itself).to_a

=> {1=>[1, 1, 1], 2=>[2], 3=>[3, 3]}
=> [[1, [1, 1, 1]], [2, [2]], [3, [3, 3]]]

[追記]

Ruby 2.7 以降をご利用の方は、
このやり方を使うと良いです。

tallyメソッドが追加されているので、こちらの方がスッキリ
https://docs.ruby-lang.org/ja/latest/method/Enumerable/i/tally.html

% ruby --version
ruby 2.7.2p137 (2020-10-01 revision 5445e04352) [x86_64-darwin20]

irb(main):001:0> ary = [1, 1, 1, 2, 3, 3]
irb(main):002:0> ary.tally
=> {1=>3, 2=>1, 3=>2}
0
0
2

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
0
0