Skip to content

Instantly share code, notes, and snippets.

@mattknox
Created August 17, 2012 20:42
Show Gist options
  • Save mattknox/3382429 to your computer and use it in GitHub Desktop.
Save mattknox/3382429 to your computer and use it in GitHub Desktop.
a function to determine whether 2 strings are anagrams, with application.
def str_to_letter_hash(str)
str.downcase.gsub(/[^a-z]/, "").split("").sort.inject(Hash.new(0)) {|m, x| m[x] += 1; m }
end
def anagrams?(s1, s2)
str_to_letter_hash(s1) == str_to_letter_hash(s2)
end
anagrams? "Mitt Romney and Paul Ryan", "My ultimate Ayn Rand Porn"
=> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment