Tuesday, April 14, 2009

Using the Perl's /e modifier at Ruby

At my last Post http://icfun.blogspot.com/2009/04/regex-to-remove-leading-zeros.html, I have mentioned that I don't know how to use the /e modifier like Perl at Ruby regular expression replacement.

But I found a way, how to handle the situation. Actually there is no /e type of modifier at Ruby like Perl. But with an example I'm showing you how to achieve if you need it. At below example, the Regexp will replace the integer with it's square value.
string = "This is a 5 ruby string";
string = string.gsub(/(\d+)/){ Integer( $1) * Integer($1) };
print string , "\n";

The output will be
This is a 25 ruby string

This is a bit tricky. Cause it just grab the $1 from the gsub() matching, and return back on a tricky way. But its handy to me. In fact, its enough for me if I need to perform such /e type of modifier at Ruby.

No comments:

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...