4

I so decided to make a palindrome program, but I did so by checking a string inputted by a user. In order to do this properly, I wanted to strip away the capitalization, spaces, and punctuation. I managed to get everything but the punctuation part of it working. Every time I try with a string like "Madam, I'm Adam" the program crashes. I am very new to Ruby, and I have only learned my knowledge through the Codecademy website. And I also using the editor provided to run my code. Every time I run it like:

puts "Enter a string!" 
user_input = gets.chomp
user_input.downcase!
user_input = user_input.gsub(/[^0-9a-z ]/i, '')
if user_input.include?(" ")
  user_input.gsub!(/ /, "")
end
if user_input == user_input.reverse
  print "Is a pallindrome"
else
  print "Is not a pallindrome"
end

It crashes. But if I run it like:

puts "Enter a string!" 
user_input = gets.chomp
user_input.downcase!
if user_input.include?(" ")
  user_input.gsub!(/ /, "")
end
if user_input == user_input.reverse
  print "Is a pallindrome"
else
  print "Is not a pallindrome"
end

It works. What a I doing wrong here? Why does my program always crash when I attempt to take away the punctuation?

S. A.
  • 3,714
  • 2
  • 20
  • 31
  • What exception does it crash with? – Chris Heald Jul 15 '14 at 00:54
  • ...and what string have you entered and on what line does the exception occur? – Cary Swoveland Jul 15 '14 at 01:01
  • Here are some other ways to check for palindromes with Ruby: http://stackoverflow.com/questions/8462512/ruby-way-to-check-for-string-palindrome – Powers Jul 15 '14 at 02:50
  • It tells me that my program has "Taken too long to run" and then asks me if I want to stop it, or try to let it continue. And, I tried using the string "Madam, I'm Adam" because the person who's going to be testing this program will most likely use that string. It crashes with any punctuation. – user3838937 Jul 15 '14 at 03:55

1 Answers1

3

Nothing is wrong with your program. Codecademy has a bug reading any input that has a quote in it...

Try it out:

gets

Just enter ' to see it crash...

My advice is to get your own local environment to develop on ruby. There are many many resources out there to help you install a simple ruby environment on any OS.

After that, download and install Sublime Text and start creating your ruby source file. Then you will see that ruby <your_file>.rb will work perfectly as you expect.

Gad
  • 41,526
  • 13
  • 54
  • 78