我在这里有一个方法,它需要一串字符串,并将这些相互对峙的字符串分组在一起,每个组形成主要anagram_groups
数组的子数组。我怎样才能简化或清理这个字谜法?
输出很好,但我觉得我的代码可能过于复杂。我的逻辑和/或语法怎么能被简化,并不能将事物重构成更多的方法?
def combine_anagrams(words)
anagram_groups = []
# For each word in array argument
words.each do |word|
# Tracking variable for the word
word_added = false
anagram_groups.each do |group|
# Check if word already exists (prevents duplicates)
if group.include? word
word_added = true
# Add word to group if it is an anagram of the first string in the group
elsif word.downcase.chars.sort == group[0].downcase.chars.sort
group << word
word_added = true
end
end
# If word was not an anagram of anything, create new group (subarray)
unless word_added
anagram_groups << [word]
word_added = true
end
end
return anagram_groups
end
这是词的测试数组:
test_words = ['cars', 'for', 'potatoes', 'racs', 'four', 'scar', 'creams', 'scream']
哇,这很简洁,看起来像group_by方法做了很多辛苦的工作。如果你不介意我问,它从哪里来?在数组的文档中我看不到任何提及它的地方。 – Inkling
请参阅[here](http://ruby-doc.org/core-2.0/Enumerable.html#method-i-group_by)。 – sawa
哦,对,谢谢。所以让我们看看我是否有这个权利:在数组上使用可枚举的方法group_by来产生数组的排序哈希值(取决于块中的内容),然后values方法取值(即子数组)从这个哈希值并将它们粘贴到一个新的数组中? – Inkling