Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove everything but characters from a string? [closed]

Tags:

ruby

I'm currently starting with ruby, and within the homework of my course it is asked to manipulate strings, which raises a question.

Given a string link this:

I'm the janitor, that's what I am!

Task is to remove everything but the characters from the string so that the result is

IamthejanitorthatswhatIam

One way to achieve this would be

"I'm the janitor, that's what I am!".gsub(" ", "").gsub(",","").gsub("'","").gsub("!","")

This works but it looks pretty clumsy. Another way to handle this task would probably be regular expressions. Is there a more "ruby"-way to achieve this?

Thanks in advance

like image 562
KernelPanic Avatar asked May 21 '26 07:05

KernelPanic


1 Answers

Use a regex instead of strings in .gsub, like /\W/, which matches non-word chars:

ruby-1.9.3-p194 :001 > x = "I'm the janitor, that's what I am!"
 => "I'm the janitor, that's what I am!" 

ruby-1.9.3-p194 :002 > x.gsub(/\W/, '')
 => "ImthejanitorthatswhatIam" 

As @nhahtdh pointed out, this includes numbers and underscores.

A regex which can accomplish this task without doing so is /[^a-zA-Z]/:

ruby-1.9.3-p194 :001 > x = "I'm the janitor, that's what I am!"
 => "I'm the janitor, that's what I am!" 

ruby-1.9.3-p194 :003 > x.gsub(/[^a-zA-Z]/, "")
 => "ImthejanitorthatswhatIam" 
like image 134
Adam Eberlin Avatar answered May 23 '26 22:05

Adam Eberlin