- 394 名前:デフォルトの名無しさん mailto:sage [2022/03/08(火) 08:30:39.25 ID:uRRrzdTb0.net]
- 配列内の要素の出現回数を求める
ary = [ 1, "a", 2, "b", "a", 1, "a" ] p results = ary.each_with_object( Hash.new( 0 ) ){ |elem, hash| hash[ elem ] += 1 } #=> { 1=>2, "a"=>3, 2=>1, "b"=>1 } Ruby には、下のPython のcollections.Counter みたいな関数がありますか? import collections l = ['a', 'a', 'a', 'a', 'b', 'c', 'c'] c = collections.Counter(l) print(c) #=> Counter({'a': 4, 'c': 2, 'b': 1}) Rubyで、誰かが作ったものはあるけど https://gist.github.com/cielavenir/501c0cf491e10d905d4307bdeb2596ea
|

|