Ruby way to group anagrams in string array Ruby way to group anagrams in string array ruby ruby

Ruby way to group anagrams in string array


Like that:

 a = ['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream'] a.group_by { |element| element.downcase.chars.sort }.values

Output is:

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

If you want to you can turn this one-liner to a method of course.


You could use the partition function instead of select, implemented in Enumerable. It splits the entries within the array according to the decision-function into two arrays.

def group_anagrams(words)  array = []  until words.empty?     word = words.first    delta, words = words.partition { |match| word.downcase.chars.sort.join.eql?(match.downcase.chars.sort.join ) } )    array += delta  end  arrayend

(untested)