→ ARGF
Today Ruby gave me a birthday present: ARGF. If you write a lot of
shell scripts you're gonna love it.
To demonstrate we'll write rcat, a dumbed down version of cat(1),
in Ruby. But first let's examine some of cat's basic functionality
using one.txt and two.txt.
$ echo 'File one!' > one.txt
$ echo 'File two :(' > two.txt
Printing a single file:
$ cat one.txt
File one!
Printing multiple files:
$ cat one.txt two.txt
File one!
File two :(
Mixing files and streams:
$ cat - two.txt < one.txt
File one!
File two :(
Okay. And rcat?
$ rcat one.txt
File one!
$ rcat one.txt two.txt
File one!
File two :(
$ rcat - two.txt < one.txt
File one!
File two :(
Great! So, how's rcat work?
$ rcat rcat
#!/usr/bin/env ruby
puts ARGF.read
Gorgeous. From the docs:
The global constant
ARGF(also accessible as$<) provides an IO-like stream which allows access to all files mentioned on the command line (or STDIN if no files are mentioned).ARGFprovides the methods#pathand#filenameto access the name of the file currently being read.
I've just rewritten mustache(1) to use ARGF. Less code, more
functionality - what else could you want for your birthday? Thanks
Ruby!