Line Filters in Ruby
A line filter is a common type of program that reads input on stdin, processes it, and then prints some derived result to stdout. grep
and sed
are common line filters.
Here’s an example line filter in Ruby that writes a capitalized version of all input text. You can use this pattern to write your own Ruby line filters.
To try out our line filter, first make a file with a few lowercase lines.
Then use the line filter to get uppercase lines.
In this Ruby version:
We use
ARGF
which is a special stream that acts as a concatenation of all the files mentioned on the command line, or uses STDIN if no files are specified.The
each_line
method onARGF
allows us to iterate over each line of input.We use
line.upcase
to convert each line to uppercase.puts
is used to print each processed line.Ruby automatically handles EOF and raises exceptions for other errors, so we don’t need explicit error checking like in the original example.
This Ruby script provides the same functionality as the original, reading lines from standard input, converting them to uppercase, and writing them to standard output.