Using Ruby's ARGF

ARGF can let you read from files and STDIN in scripts. It's really convenient, but I also find it a little awkward. Most of its methods provide ways to access the files and STDIN (I'll say "inputs" from now on) as one concatenated string instead of each one distinctly.

I found a blog post that suggested using ARGF.file.size to read the correct amount of data from ARGF.read(size), and to call it repeatedly to eventually read all of the data. Sadly, while instances of File have a size method, instances of IO don't (ARGF.file returns an instance of either File or IO).

I poked around and found that ARGF.file.read works for both kinds of inputs. It only returns the current input's contents, regardless of type. After getting its contents, we can use ARGF.skip to move on to the next file. And when ARGF is .closed?, we know we read everything. I added a ARGF.eof? just in case, but it doesn't seem necessary so far.

loop do
  break if ARGF.closed? || ARGF.eof?

  pp ARGF.filename
  pp ARGF.file.read
  ARGF.skip
end

See also:

Posted on 2021-03-21 09:30 PM
Contact
hello(at)zachahn(dot)com
© Copyright 2008–2021 Zach Ahn