0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

group_byメソッドの使い所について

Posted at

みなさまこんにちは、プレイライフの熊崎です!

先週の土曜日にコロナワクチンの2回目接種を行ったのですが、3日ほど寝込んでしまいました。
ファイザーでも38℃くらい熱が出たので、かなり辛かったです。ですので、まだ受けていない方は事前に解熱剤を買っておくと良いかもしれません。

といったお話は置いといて、今日もメソッドのアウトプットを行っていきます。

group_byメソッドとは

ブロックを評価した結果をキー、対応する要素の配列を値とするハッシュを返す。
参考URL:https://docs.ruby-lang.org/ja/latest/method/Enumerable/i/group_by.html

以下のような挙動を示す。

sample.rb
(1..6).group_by {|i| i%3}   #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}
# 参考URL:https://docs.ruby-lang.org/ja/latest/method/Enumerable/i/group_by.html

各要素を3で割った時の余りの数をキーにして、余りの数が同じもの同士をグルーピングしている。
またEnumerableモジュールのメソッドのため、EnumerableモジュールをincludeしているArray,Hash,Range,Enumeratorクラスで使用可能。

どんな時に使うのか?

→ ブロックを評価した結果に応じて要素を振り分けたいとき

具体例:学校のテスト

田中君と佐藤君と鈴木君がいて、テストの合格点は60点。田中君は70点、鈴木君は80点なので、合格。佐藤君は50点なので不合格とする。合格者と不合格者を分けたい。

sample.rb
students = [
          {name: "田中", score: 70},
          {name: "佐藤", score: 50},
          {name: "鈴木", score: 80},
        ]

students.group_by { |s| s[:score] >= 60 ? "合格者" : "不合格者" }
# => {"合格者"=>[{:name=>"田中", :score=>70}, {:name=>"鈴木", :score=>80}], "不合格者"=>[{:name=>"佐藤", :score=>50}]}

参考文献

https://docs.ruby-lang.org/ja/latest/method/Enumerable/i/group_by.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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?