Group by identity in Ruby

ぐ巨炮叔叔 提交于 2020-01-02 05:56:50

问题


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


来源:https://stackoverflow.com/questions/33887596/group-by-identity-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!