0
0
RubyProgramBeginner · 2 min read

Ruby Program to Check Anagram with Examples and Explanation

In Ruby, you can check if two strings are anagrams by comparing their sorted characters using str1.chars.sort == str2.chars.sort.
📋

Examples

Input"listen", "silent"
Outputtrue
Input"hello", "world"
Outputfalse
Input"aabbcc", "abcabc"
Outputtrue
🧠

How to Think About It

To check if two words are anagrams, think about whether they have the same letters in the same amounts. If you sort the letters of both words, they should look exactly the same if they are anagrams.
📐

Algorithm

1
Get two input strings.
2
Convert both strings to arrays of characters.
3
Sort both arrays alphabetically.
4
Compare the sorted arrays.
5
Return true if they are equal, otherwise false.
💻

Code

ruby
def anagram?(str1, str2)
  str1.chars.sort == str2.chars.sort
end

puts anagram?("listen", "silent")  # true
puts anagram?("hello", "world")   # false
puts anagram?("aabbcc", "abcabc") # true
Output
true false true
🔍

Dry Run

Let's trace the example anagram?("listen", "silent") through the code

1

Input strings

str1 = "listen", str2 = "silent"

2

Convert to character arrays

str1.chars = ["l", "i", "s", "t", "e", "n"], str2.chars = ["s", "i", "l", "e", "n", "t"]

3

Sort character arrays

str1.chars.sort = ["e", "i", "l", "n", "s", "t"], str2.chars.sort = ["e", "i", "l", "n", "s", "t"]

4

Compare sorted arrays

Both sorted arrays are equal

5

Return result

true

Iterationstr1.chars.sortstr2.chars.sortEqual?
1["e", "i", "l", "n", "s", "t"]["e", "i", "l", "n", "s", "t"]true
💡

Why This Works

Step 1: Convert strings to arrays

Using chars splits the string into individual letters so we can compare them easily.

Step 2: Sort the arrays

Sorting arranges letters in order, so anagrams will have identical sorted arrays.

Step 3: Compare sorted arrays

If both sorted arrays match exactly, the strings are anagrams; otherwise, they are not.

🔄

Alternative Approaches

Using character frequency count
ruby
def anagram?(str1, str2)
  str1.chars.tally == str2.chars.tally
end

puts anagram?("listen", "silent")  # true
puts anagram?("hello", "world")   # false
This method counts how many times each letter appears and compares counts, which can be faster for very long strings.
Using regular expressions to ignore spaces and case
ruby
def anagram?(str1, str2)
  clean1 = str1.downcase.gsub(/\s+/, '')
  clean2 = str2.downcase.gsub(/\s+/, '')
  clean1.chars.sort == clean2.chars.sort
end

puts anagram?("Listen", "Silent")  # true
puts anagram?("Hello", "World")   # false
This approach ignores spaces and letter case, useful for phrases.

Complexity: O(n log n) time, O(n) space

Time Complexity

Sorting the characters takes O(n log n) time, where n is the length of the string. This dominates the runtime.

Space Complexity

Extra space is needed to store the character arrays and their sorted versions, which is O(n).

Which Approach is Fastest?

Counting characters with tally can be faster (O(n)) than sorting, but sorting is simpler and more readable for beginners.

ApproachTimeSpaceBest For
Sorting charactersO(n log n)O(n)Simple and readable code
Counting characters (tally)O(n)O(n)Large strings with performance needs
Sorting with cleaning (ignore case/space)O(n log n)O(n)Checking phrases ignoring spaces and case
💡
Use chars.sort to quickly check anagrams by comparing sorted letters.
⚠️
Forgetting to handle case sensitivity or spaces can cause false negatives when checking anagrams.