5

I am new to ruby and my regex knowledge leaves a lot to be desired. I am trying to check if a string is a palindrome, but wish to ignore white space and commas.

The current code I have is

def palindrome(string)
  string = string.downcase
  string = string.gsub(/\d+(,)\d+//\s/ ,"")
  if string.reverse == string
    return true
  else
    return false
  end
end

Any assistance here would be greatly appreciated.

Tom Lord
  • 27,404
  • 4
  • 50
  • 77
Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54
  • You want `"pat, tap"` to return `true`? Note that the body of your can be written as a single line: `string.downcase.gsub(/\d+(,)\d+//\s/ ,"") == string`. You don't need `return` as the last calculated value is returned. – Cary Swoveland Feb 08 '15 at 20:50

2 Answers2

13

but wish to ignore white space and commas

You don't need to put \d in your regex. Just replace the spaces or commas with empty string.

string = string.gsub(/[\s,]/ ,"")

The above gsub command would remove all the spaces or commas. [\s,] character class which matches a space or comma.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

Another way would be to use the method String#tr:

str = "pat, \t \ntap"

str.tr(" ,\t\n", '') #=> "pattap"
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100