我已经阅读了类似问题的所有答案,但我仍然无法让它为我工作。
这是我为查找和分组句子的字谜而编写的代码:
"scream cars for four scar creams"
预期输出为:
OUTPUT: ["cars", "scar"]
def anagram_groups
result = []
here = self.gsub(/\W/," ").downcase.split(" ")
here = self.split(" ")
here.each do |y|
#result == here.group_by{|w| w.chars.sort}.values
result == here.select {|x| x.chars.sort == y.chars.sort}
end
result
end
我尝试了两种不同的方法,但它们似乎都不适合我。
答案 0 :(得分:10)
以下是如何做到这一点:
str = "scream cars for four scar creams"
str.split.group_by{|a| a.chars.sort}.select{|k,v| v.size > 1 }.values
# => [["scream", "creams"], ["cars", "scar"]]