2013-05-19 39 views
0

我在这里有一个方法,它需要一串字符串,并将这些相互对峙的字符串分组在一起,每个组形成主要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'] 

回答

3
test_words.group_by{|w| w.each_char.sort}.values 

会给

[ 
    ["cars", "racs", "scar"], 
    ["for"], 
    ["potatoes"], 
    ["four"], 
    ["creams", "scream"] 
] 
+0

哇,这很简洁,看起来像group_by方法做了很多辛苦的工作。如果你不介意我问,它从哪里来?在数组的文档中我看不到任何提及它的地方。 – Inkling

+0

请参阅[here](http://ruby-doc.org/core-2.0/Enumerable.html#method-i-group_by)。 – sawa

+0

哦,对,谢谢。所以让我们看看我是否有这个权利:在数组上使用可枚举的方法group_by来产生数组的排序哈希值(取决于块中的内容),然后values方法取值(即子数组)从这个哈希值并将它们粘贴到一个新的数组中? – Inkling

0

我修改泽圭太的回答略有以忽略大小写,并确保有没有重复值:

test_words.group_by{|w| w.downcase.each_char.sort}.values.each{|v| v.uniq!} 

我意识到如果单词有不同情况的字符,这仍然会在输出中给出重复项,但这对我的目的来说很好。现在我全部排序了,谢谢!