remove both commas and white space ruby

Paul Fitzgerald picture Paul Fitzgerald · Feb 8, 2015 · Viewed 8.5k times · Source

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.

Answer

Avinash Raj picture Avinash Raj · Feb 8, 2015

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.