Tuesday, February 19, 2008

Ruby Code Snippets #1

Here's yet another reason I find ruby so easy to code. Lets assume that you want to do filtering of a certain kind of input that is demarcated by 'START' and 'END' on a separate line by itself. Let's use an example like the data shown below:
This is an unwanted line 1.
This is an unwanted line 2.
START
This is a wanted line 1.
This is a wanted line 2.
END
This is an unwanted line 3.
This is an unwanted line 4.
Normally, the typical way of segregating the wanted lines with the unwanted ones is probably via writing code that logically looks something like this:
in_header = false         # variable to remember whether if in_header
while line = STDIN.gets
if line =~/^START$/ # found header, start trapping
in_header = true
elsif line =~/^END$/ # end header, stop trapping
print line # have to print the line boundary inclusive
in_header = false
end
if in_header # still in boundary, print line
print line
end
end
But in ruby, the idea of applying ranges on regular expression matches simplifies the syntax down to a bare minimum:
while line = STDIN.gets
if line =~ /^START$/ .. line =~ /^END$/
print line
end
end
This is one of the things that I have seen that's unlike any other language I've encountered before. Amazing and totally delightful!

0 comments:

Post a comment