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, ARGF.file returns an instance of either File or IO, and only instances of File has a size method. This means that reading from STDIN only works if it’s the last input.

I poked around and found that both kinds of instances have a #read method that only returns the current input’s contents. After getting its contents, we can use ARGF.skip to move on to the next input. 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.

files = {}
loop do
  break if ARGF.closed? || ARGF.eof?

  files[ARGF.filename] = ARGF.file.read
  ARGF.skip
end

See also:

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