Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by identity in Ruby

How does Ruby's group_by() method group an array by the identity (or rather self) of its elements?

a = 'abccac'.chars
# => ["a", "b", "c", "c", "a", "c"]

a.group_by(&:???)
# should produce...
# { "a" => ["a", "a"],
#   "b" => ["b"],
#   "c" => ["c", "c", "c"] }
like image 982
sschmeck Avatar asked Nov 24 '15 07:11

sschmeck


2 Answers

In a newer Ruby (2.2+?),

a.group_by(&:itself)

In an older one, you still need to do a.group_by { |x| x }

like image 185
Amadan Avatar answered Sep 19 '22 15:09

Amadan


Perhaps, this will help:

a = 'abccac'.chars
a.group_by(&:to_s)
#=> {"a"=>["a", "a"], "b"=>["b"], "c"=>["c", "c", "c"]}

Alternatively, below will also work:

a = 'abccac'.chars
a.group_by(&:dup)
#=> {"a"=>["a", "a"], "b"=>["b"], "c"=>["c", "c", "c"]}
like image 33
Wand Maker Avatar answered Sep 23 '22 15:09

Wand Maker