7
9

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 5 years have passed since last update.

[ ruby ] group_byを使う

Last updated at Posted at 2015-12-10

0. やりたいこと

group_byで返されるhashのキーをカスタマイズしたい。

1. よくあるサンプル

これだと返却されるhashのキーを自分で決めることができない
(1..5).group_by {|x| x%2}
=> {1=>[1,3,5], 0=>[2, 4]}

2. 解決案

group_byは配列の要素をグルーピングする。

グルーピング=「評価した結果に応じて仕分ける」。

評価結果が返却されるhashのキーとなる。

要するに評価された配列の要素が評価結果のキーごとに分類される。

キーを自分で決めたければ評価するメソッドを自分で作るしかない。

def evaluate_num(val)
  return "RED"  if val <= 2
  return "BLUE" if val > 2
end
(1..5).group_by {|x|
          evaluate_num(x)
       }
=> {"RED"=>[1,2], "BLUE"=>[3, 4, 5]}
7
9
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
7
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?