我在這裏有一個方法,它需要一串字符串,並將這些相互對峙的字符串分組在一起,每個組形成主要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