String Has Other Methods Besides =~ and sub()

Posted over 5 years ago in Early Steps and Ruby Tutorials.

Ask anyone who knows me and they will tell you I'm a huge fan of regular expressions. I use them all the time and my FasterCSV library is a regular expression powered parser. However, even I know they are not for everything, and lately I keep running into almost comical examples of misuse. Here are some of my favorites.

First, we have:

str =~ /=/

That snippet is like calling for a military escort (the regular expression engine) to see you safely to the grocery store down the block. That's fun, but probably overkill. In this case, a call to include?() will do the trick:

str.include?("=")

That may be more like riding you bike to the grocery store, but it gets the job done and is a bit faster to boot.

Funny example number two. I've seen this before:

str =~ /\Aquit\Z/

Again, the regular expression engine appreciates the love, but you really just want ==:

str == "quit"

Even for some of the fancier stuff, you don't need a full blown regular expression. For example, this:

str.sub(/\D+/, "")

could be:

str.delete("^0-9")  # no, that's not a regex

You get the idea. I'm not trying to ban regular expressions. Instead, I just think people should remember there are a lot of other methods in String. When you have a few moments, look up these guys in the documentation:

  • String#[]= # can take a regex, but has other fun options
  • String#count
  • String#index # can take a regex
  • String#squeeze
  • String#rindex # can take a regex
john added 1 day later:

you are my programming star.

dekay added 9 days later:

Your feeds are broken? feedvalidator won't even hit the page…

James Edward Gray II added about 1 month later:

Feeds should be fixed now. Sorry for the downtime.

Add Your Thoughts

You can use Markdown in the body of your comment to format text and make links.

Note that I reserve the right to edit any content you post here. I typically exercise this right to fix formatting issues. All posts must be approved so spam will never be seen on these pages.

Author:
URL or Email (optional):
Body: