Tuesday, 26 February 2013

Ruby ARGF and the "<" operator

One of those things I've always should have known but somehow skipped when first read about ARGV and ARGF on Ruby.

ARGF will give you file handlers and content of all files passed to the script, but it assumes that all arguments present in ARGV are in fact files.
So if you want to be able to call your script like so:

./myrubyscript 100 file.txt

Than in the code you must have:


somvar     = ARGV.shift.to_i
filelines  = ARGF.readlines


How about, if for some reason, you want to call your script like so:

./myrubyscript 100 < file.txt



somvar     = ARGV.shift.to_i
filelines  = ARGF.readlines



It's the same code! Don't you love Ruby?

The workings:
The arguments passed to your script are stored in the ARGV Array, one argument per element. ARGF assumes that any arguments that aren't file names have been removed from ARGV.
It took me more than it should have to find this little page.