String Replacement in Ruby

If you’re used to other programming languages, you’re likely looking for some sort of replace function in your strings to replace bits with other bits. But skimming through the String RDoc, you don’t find anything like that, right?

There are a couple of options you have available to you. The first is the tr function; you pass in sets of characters, and it replaces them with other characters. For example, if you wanted to replace all vowels with an asterick, you could write:

"hello".tr("aeiou", "*") # => "h*ll*

On the other hand, if you wanted to remove all kinds of symbols–something useful–you could write something like:

"test: !@#$%^&*()_+ done!".tr("!@#$%^&*()_+", "") # => "test: done"

Clearly, some powerful stuff.

But what if you want a more natural approach to string replacement–replacing words or string fragments with other words or string fragments? For example, maybe you want to replace all instances of the bold tag with the strong tag.

You can use the gsub method; it takes a regular expression, and does a global (string-wide) replacement. Let’s say we want to remove all numbers from a string. We can do it with tr; but what about removing all two-digit numbers? gsub to the rescue!

"There were 13 hamsters, 29 dogs, 3 cats, 5 melons, and 72 mice.".gsub(/[0-9][0-9]/, 'some') # => "There were some hamsters, some dogs, 3 cats, 5 melons, and some mice."

Since it uses regular expressions, you can do all kinds of strange and complicated stuff. The limitations are only your imagination (and regular-expression capability)!

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Development and tagged , , . Bookmark the permalink.

Comments are closed.