我想根据内容分组数组的字符串元素。
["abc", "abc", "def", "ghi", "ghi"].group_by { |x| some code }
所以我希望它返回:
[["abc", "abc", "abc"],["def"],["ghi", "ghi"]]
我尝试了以下内容:
irb(main):065:0> ["abc", "abc", "def", "ghi", "ghi"].group_by { |x| x }
返回:{"abc"=>["abc", "abc"], "def"=>["def"], "ghi"=>["ghi", "ghi"]}
最好的方法是什么?
答案 0 :(得分:2)
你只想要一个数组。然后你写:
["abc", "abc", "def", "ghi", "ghi"].group_by { |x| x }.values
答案 1 :(得分:2)
class Array
def group
h_result = {}
self.uniq.each_with_index {|value, i| h_result[i] = self.select{|x| x==value}}
group = h_result
end
end
a_test = ["abc", "abc", "def", "ghi", "ghi"]
h_test = a_test.group
puts h_test.inspect
答案 2 :(得分:1)
a = ["abc", "abc", "def", "ghi", "ghi"]
Hash[a.uniq.map.with_index{|e,i| [i,[e]*a.count(e)]}]
# => {0=>["abc", "abc"], 1=>["def"], 2=>["ghi", "ghi"]}
答案 3 :(得分:0)
这是一个愚蠢的单行,可以得到你想要的东西。但是,看起来仍然有点傻。
a = ["abc", "abc", "def", "ghi", "ghi"]
Hash[a.group_by { |x| x }.values.map.with_index { |x, i| [i, x] }]
# => {0=>["abc", "abc"], 1=>["def"], 2=>["ghi", "ghi"]}
答案 4 :(得分:0)
不是很简单,但它会做你想要的:
["abc", "abc", "def", "ghi", "ghi"].group_by{|x|x}.each_with_index.inject({}){|m,a|m[a[1]]=a[0];m}