Archive for the ‘ruby’ Category

Solving the Anagram-Game in Ruby

Posted: March 5, 2012 in ruby


(Excerpted from Wikipedia). An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; for example orchestra can be rearranged into carthorse

class NoElementsInArrayError < StandardError ; end

  def combine_anagrams(words)
  raise NoElementsInArrayError unless words.length > 0

  h =
  words.each_index do |x|
    sorted_word =  # ==> [acrs, for, aeoopstt, acrs, foru, acrs, acemrs, acemrs]
    unless h.has_key?(sorted_word)                      # creates an empty new array as value for key "acrs", "for" and so on...
      h[sorted_word] =

  h.fetch(sorted_word).push(              # populates the array for key "acrs", "for" and so on...

  result =
  h.each_value {|value| result.push(value) }
  return result


example:   combine_anagrams(['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams','scream'])

enjoy it!