10

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"] }
sschmeck
  • 7,233
  • 4
  • 40
  • 67

2 Answers2

26

In a newer Ruby (2.2+?),

a.group_by(&:itself)

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

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • 2
    Thanks, here is the documentation link to [Object#itself()](http://ruby-doc.org/core-2.2.0/Object.html#method-i-itself) in Ruby 2.2. BTW I used `&:to_s` to provide the example above. – sschmeck Nov 24 '15 at 07:30
1

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"]}
Wand Maker
  • 18,476
  • 8
  • 53
  • 87