Why Ruby Continues to Rock

Originally posted March 11, 2008 at masonbrowne.info:

So I was doing a little text substitution today. After learning that String#match only returns the first occurrence, I started looking for other solutions. Since I wasn't substituting one string for another, but instead substituting a manipulation based on the match, I hadn't even considered String#gsub. But then I thought for a moment. String#gsub took two arguments, a regex and a string to substitute it with (among other options). Could I substitute the second parameter with a block that returns the replacement value? Fired up the Rails console (I was already in a Rails project) and tried:

                    "hello".gsub(/l/){|m| "f"}
                  

And sure enough, I got back heffo. In the Ruby community, there is a term for this: POLS, or the Principle Of Least Surprise. Once again, the language lives up to this standard.

Thanks, Matz.