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.
# We don't need to explicitly import libraries in Ruby
# as they are automatically available
# Wrap STDIN with a buffered reader
ARGF.each_line do |line|
# Convert the line to uppercase
ucl = line.upcase
# Write out the uppercased line
puts ucl
end
# Check for errors during reading
# In Ruby, exceptions are raised automatically, so we don't need to check explicitly
To try out our line filter, first make a file with a few lowercase lines.
$ echo 'hello' > /tmp/lines
$ echo 'filter' >> /tmp/lines
Then use the line filter to get uppercase lines.
$ cat /tmp/lines | ruby line_filters.rb
HELLO
FILTER
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.