ssc*_*eck 4 ruby grouping identity
Ruby的group_by()方法如何通过self其元素的标识(或更确切地说)对数组进行分组?
a = 'abccac'.chars
# => ["a", "b", "c", "c", "a", "c"]
a.group_by(&:???)
# should produce...
# { "a" => ["a", "a"],
# "b" => ["b"],
# "c" => ["c", "c", "c"] }
Run Code Online (Sandbox Code Playgroud)
Ama*_*dan 14
在较新的Ruby(2.2 +?)中,
a.group_by(&:itself)
Run Code Online (Sandbox Code Playgroud)
在较旧的一个,你仍然需要做 a.group_by { |x| x }