Loading...
If the page contents do not appear, it may mean that JavaScript is disabled in your browser. Please enable JavaScript to view this.
An Article from Aaron's Article ArchiveJust What I Needed: Match-Returning String Substitution Photo: Sculpted SandIPv4You are not logged in. Click here to log in. | |
Use Google to search aarongifford.com:
Here is one of my web log entries, perhaps from my Yakkity Yak page, What's New page, or one of my Astounding Adventures from my Geocaching section: Just What I Needed: Match-Returning String Substitution
Tuesday, 12 June 2007 6:03 PM MDT
Yakkity Yak
I'm posting this from work, so this is your geekiness warning.
I've been working on some ruby scripts and I really could use a method in ruby's String class that does what String#sub! does but instead of returning the modified String returns the MatchData from the Regex that was String#sub!'s first argument.
Also, when passed a block of code, I wanted the MatchData passed to the block as the argument, not the string of the entire match.
So here's what I came up with:
class String
def matchsub!(*sym, &blk)
unless (blk.nil? ? (sym.size == 2) : (sym.size == 1))
raise ArgumentError.new(
"wrong number of arguments (#{sym.size} for " + (blk.nil? ? '2' : '1') + ')'
)
end
unless (sym[0].is_a?(Regexp))
raise TypeError.new(
"wrong argument type #{sym[0].class} (expected Regexp)"
)
end
m = sym[0].match(self)
return nil if (m.nil?)
s = blk.nil? ? sym[1] : blk.call(m)
self.replace(m.pre_match + s + m.post_match)
return m
end
end
Yes, I could have just used $~ (a.k.a. $LAST_MATCH_INFO when using require 'english') after calling String#sub!.
For example: String method:String class and one is able to avoid using $ variables.
Yes, there are other ways to accomplish the same thing using $1..$9, but for me, coming to ruby from perl, I like to avoid as much $ clutter as possible so my ruby code looks less perl-ish.
| |
Copyright © 1993-2012 - Aaron D. Gifford - All Rights Reserved | |