Saari Development

This blog is intended to be a log of my (Ali Rizvi's) professional ramblings as a software development engineer. I intend to add logs of my experience with different technologies, software, tech books/articles and related stuff from time to time. My intention is to have an archive for my personal use and public benefit.

Sunday, December 30, 2007

Ruby: One liner to strip the line number from code posted

In response to my previous post my friend Arsalan posted his C# solution on my shared friend blog SaarayDost

Both my solution and his had line numbers with the code which makes it easy to reference a line number in a discussion but if you want to run and test code it can be painful to strip them out one by one.

I wrote the following quick ruby one liner that can be run on a file after copy-pasting the code and saving it.

ruby -lne 'puts $_.gsub(/^\s?\d+:?/, "")' ali.rb > ali.rb

I am sure there good be a better more clever way to do this after all TIMTOWDI but here I use the l to remove newline at the end of each line, n to iterate over the given file one line at a time and e to execute the following code string (in quotes, on each line). $_ is the magic variable (a perl legacy in ruby) that magically populated, in this case with the current line of file being processed. gsub simply removed the pattern match in the first argument by the string in the second argument.

While searching for a good description of $_ I also found this interesting link with other useful ruby one-liners.

Update: found another way to achieve the above result. -p option prints the $_ at the end of each iteration.

ruby -lpe '$_.gsub!(/^\s?\d+:?/, "")' ali.rb > ali.rb

0 Comments:

Post a Comment

<< Home