def search_and_sort (words, num)
words.map{|a| a if a.split("").sort.join == num.split("").sort.join}.compact
end
def combine_anagrams(words)
words.map{|a| search_and_sort(words, a)}.uniq
end
p combine_anagrams(['cars', 'for', 'potatoes', 'racs', 'four', 'scar', 'creams', 'scream'] )
#==>[["cars", "racs", "scar"], ["for"], ["potatoes"], ["four"], ["creams", "scream"]]
答案 0 :(得分:3)
你想要的是Enumerable的group_by
方法:
def combine_anagrams(words)
words.group_by do |word|
word.chars.sort.join
end.values
end
这种方法可以很容易地按任意标准对事物进行分组。