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 explicitlyTo try out our line filter, first make a file with a few lowercase lines.
$ echo 'hello' > /tmp/lines
$ echo 'filter' >> /tmp/linesThen use the line filter to get uppercase lines.
$ cat /tmp/lines | ruby line_filters.rb
HELLO
FILTERIn this Ruby version:
We use
ARGFwhich 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_linemethod onARGFallows us to iterate over each line of input.We use
line.upcaseto convert each line to uppercase.putsis 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.