Skip to content

Instantly share code, notes, and snippets.

@royzinn
Last active December 24, 2015 18:19
Show Gist options
  • Save royzinn/6842266 to your computer and use it in GitHub Desktop.
Save royzinn/6842266 to your computer and use it in GitHub Desktop.
Anagram with Hash#inject
# taking a list of words (space delimited) and groups them if they're anagrams
# example input: star mary demo hops rats posh tars mode else army shop demo will return:
# "rats star tars"
# "army mary"
# "demo demo mode"
# "hops posh shop"
# "else"
def anagrams
words = gets.chomp.split
anagrams_hash = words.inject({}) {|h,w| h[w.chars.sort.join] ? h[w.chars.sort.join] << w : h[w.chars.sort.join] = [w]; h}
anagrams_hash.each {|k,v| p v.sort.join(" ")}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment