Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove both commas and white space ruby

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.

like image 909
Paul Fitzgerald Avatar asked Feb 08 '15 16:02

Paul Fitzgerald


People also ask

How do you get rid of white space in Ruby?

Ruby has lstrip and rstrip methods which can be used to remove leading and trailing whitespaces respectively from a string. Ruby also has strip method which is a combination of lstrip and rstrip and can be used to remove both, leading and trailing whitespaces, from a string.

What does .strip do in Ruby?

The . strip method removes the leading and trailing whitespace on strings, including tabs, newlines, and carriage returns ( \t , \n , \r ).

How do you remove commas in regex?

To remove all commas from a string, call the replace() method, passing it a regular expression to match all commas as the first parameter and an empty string as the second parameter. The replace method will return a new string with all of the commas removed.

How do you delete a new line character in Ruby?

delete or . tr String method to delete the newlines.


2 Answers

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.

like image 182
Avinash Raj Avatar answered Sep 28 '22 07:09

Avinash Raj


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

str = "pat, \t \ntap"

str.tr(" ,\t\n", '') #=> "pattap"
like image 34
Cary Swoveland Avatar answered Sep 28 '22 07:09

Cary Swoveland