Check If Two Strings Are Anagrams In Ruby
Determine whether two strings contain the same characters in any order.
Description
An anagram is a word or phrase formed by rearranging the letters of another. The idiomatic Ruby approach sorts both strings’ characters and compares — O(n log n) and readable. For case-insensitive checks, downcase before sorting. For performance on large inputs, a character frequency hash comparison runs in O(n).
Sample input:
"listen"
"silent"
Sample Output:
true
Answer
# Sort-based — readable and idiomatic
def anagram?(a, b)
a.downcase.chars.sort == b.downcase.chars.sort
end
anagram?("listen", "silent") # => true
anagram?("hello", "world") # => false
anagram?("Astronomer", "Moon starer") # ignores spaces? No — add gsub first:
def anagram_phrase?(a, b)
normalize = ->(s) { s.downcase.gsub(/\s+/, "").chars.sort }
normalize.(a) == normalize.(b)
end
anagram_phrase?("Astronomer", "Moon starer") # => true
# Frequency hash — O(n), useful for very long strings
def anagram_fast?(a, b)
a.downcase.chars.tally == b.downcase.chars.tally
end
Check viewARU - Brand Newsletter!
Newsletter to DEVs by DEVs - boost your Personal Brand & career! 🚀