ruby - How can I simplify or clean up this anagram method? -


i have method here takes array of strings , groups ones anagrams of each other together, each group forming sub-array of main anagram_groups array.

the output fine feel code overly-complicated. how logic and/or syntax simplified, short of refactoring things more methods?

def combine_anagrams(words)   anagram_groups = []   # each word in array argument   words.each |word|      # tracking variable word     word_added = false      anagram_groups.each |group|       # check if word exists (prevents duplicates)       if group.include? word         word_added = true       # add word group if anagram of first string in group       elsif word.downcase.chars.sort == group[0].downcase.chars.sort         group << word         word_added = true               end     end      # if word not anagram of anything, create new group (subarray)     unless word_added       anagram_groups << [word]       word_added = true     end    end   return anagram_groups end 

this array of words testing:

test_words = ['cars', 'for', 'potatoes', 'racs', 'four', 'scar', 'creams', 'scream'] 

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

would give

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

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -