Ruby Program to Check Palindrome String
You can check a palindrome in Ruby by comparing a string with its reverse using
str == str.reverse. For example: puts 'madam' == 'madam'.reverse prints true.Examples
Inputmadam
Outputtrue
Inputhello
Outputfalse
InputA man a plan a canal Panama
Outputfalse
How to Think About It
To check if a string is a palindrome, think about reading it forwards and backwards. If both are the same, the string is a palindrome. We can reverse the string and compare it to the original to decide.
Algorithm
1
Get the input string.2
Reverse the string.3
Compare the original string with the reversed string.4
If both are equal, return true; otherwise, return false.Code
ruby
puts 'Enter a string:' str = gets.chomp if str == str.reverse puts 'true' else puts 'false' end
Output
Enter a string:
madam
true
Dry Run
Let's trace the input 'madam' through the code
1
Input string
str = 'madam'
2
Reverse string
str.reverse = 'madam'
3
Compare original and reversed
'madam' == 'madam' is true
4
Print result
Output: true
| Original String | Reversed String | Comparison Result |
|---|---|---|
| madam | madam | true |
Why This Works
Step 1: Reverse the string
Using str.reverse creates a new string with characters in reverse order.
Step 2: Compare strings
The original string and reversed string are compared with == to check equality.
Step 3: Return result
If both strings match, the string is a palindrome, so we print true; otherwise, false.
Alternative Approaches
Using a loop to compare characters
ruby
puts 'Enter a string:' str = gets.chomp is_palindrome = true (0...str.length / 2).each do |i| if str[i] != str[-i - 1] is_palindrome = false break end end puts is_palindrome
This method checks characters one by one without creating a reversed string, saving memory for very long strings.
Ignoring case and spaces
ruby
puts 'Enter a string:' str = gets.chomp.downcase.gsub(/\s+/, '') puts str == str.reverse
This approach ignores case and spaces, useful for phrases like 'A man a plan a canal Panama'.
Complexity: O(n) time, O(n) space
Time Complexity
Reversing the string takes O(n) time where n is the string length, and comparing takes O(n) as well, so overall O(n).
Space Complexity
Reversing creates a new string of length n, so space complexity is O(n). The loop method uses O(1) extra space.
Which Approach is Fastest?
The direct reverse and compare method is simple and fast for most cases. The loop method saves space but is more complex.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Reverse and compare | O(n) | O(n) | Simple and readable code |
| Loop character comparison | O(n) | O(1) | Memory efficient for large strings |
| Ignoring case and spaces | O(n) | O(n) | Checking phrases ignoring formatting |
Use
str == str.reverse for a quick palindrome check in Ruby.Forgetting to remove spaces or ignore case when checking phrases can cause false negatives.