Group by identity in Ruby

2019-05-10 10:25发布

问题:

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"] }

回答1:

In a newer Ruby (2.2+?),

a.group_by(&:itself)

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



回答2:

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"]}