16
JUL2006
String Has Other Methods Besides =~/match() and sub()
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 your 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)
Comments (3)
-
john July 18th, 2006 Reply Link
You are my programming star.
-
Your feeds are broken? feedvalidator won't even hit the pageā¦
-
Feeds should be fixed now. Sorry for the downtime.
-