在Ruby中按身份分组 [英] Group by identity in Ruby
本文介绍了在Ruby中按身份分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Ruby的 group_by()
方法是根据数组元素的标识(或更确切地说是self
)对数组进行分组?
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"] }
推荐答案
在较新的Ruby(2.2+?)中,
In a newer Ruby (2.2+?),
a.group_by(&:itself)
在较老的版本中,您仍然需要执行a.group_by { |x| x }
In an older one, you still need to do a.group_by { |x| x }
这篇关于在Ruby中按身份分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文