LoginSignup
0
0

More than 1 year has passed since last update.

Rubyで同じ要素をカウントするメソッド

Posted at

概要

rubyで同じ要素をカウントするプログラムを考えていたときに、リファレンスにあったメソッドについてです。

tally

はじめは、以下のようなプログラムを考えていました。

fruits = ["apple", "grape", "orange", "banana", "orange", "apple"]

# 重複をなくす 
p fruits_uniq = fruits.uniq

# ["apple", "grape", "orange", "banana"]


# 種類ごとにカウントする 
fruit_list = {}
fruits_uniq.each do |s| 
   fruit_list[s] = fruits.count(s)
end
p fruit_list

# {"apple"=>2, "grape"=>1, "orange"=>2, "banana"=>1}

これを1行でできるメソッドがtallyメソッドになります。

fruits.tally

# {"apple"=>2, "grape"=>1, "orange"=>2, "banana"=>1}

tallyメソッドは、selfに含まれる要素数の結果をHashで返してくれます。
あったらいいなというメソッドは調べてみると案外あることがわかりました。

https://docs.ruby-lang.org/ja/latest/method/Enumerable/i/tally.html)

0
0
0

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