How to check if two strings are anagrams (same letters, different words) in Ruby

1 Answer

0 votes
#
# Check whether two strings are anagrams.
#
# Approach:
#   1. Normalize both strings:
#      - Convert to lowercase.
#      - Remove any non‑letter characters.
#      - Split into characters.
#
#   2. Count character frequencies using `tally`.
#      This produces a Hash like { "a" => 2, "b" => 1 }.
#
#   3. Compare the two frequency hashes.
#      If they match, the strings contain the same letters.
#

# Normalize a string into a clean, letter‑only lowercase array
def normalize(str)
  str.downcase.scan(/[a-z]/)
end

# Determine whether two strings are anagrams
def anagram?(a, b)
  normalize(a).tally == normalize(b).tally
end

# Example usage
s1 = "Listen"
s2 = "Silent"

if anagram?(s1, s2)
  puts "Result: \"#{s1}\" and \"#{s2}\" are anagrams."
else
  puts "Result: \"#{s1}\" and \"#{s2}\" are NOT anagrams."
end



#
# run:
#
# Result: "Listen" and "Silent" are anagrams.
#

 



answered Aug 20 by avibootz
...