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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With