I’ve started learning Ruby and trying to do the first (stupid) program
as exercise.
The input will be supported from a file and/or stdin.
If no file given, the program prompt user to insert all the data.
If a file is given, it expects line with at least two integers and will
read until the first bad line. After that, we expect another valid line.
If while reading the first sequence the file(s) end, a feature require
the user to insert some other data.
And there’s the problem!
There’s a sample program:
while line = gets
n1, n2 = line.scan(/\d+/).map(&:to_i)
break unless n2
… processing …
end
At first try, the condition was ARGF.eof? but it will raise IOError.
How and when I’ve to use eof? method?
if ARGF.closed?
tell user what to do
end
n1, n2 = gets.scan(/\d+/).map(&:to_i) # Raise: NoMethodError on Nil
class
Also if ARGV is empty, ARGF doesn’t swap to STDIN and gets continue to
return nil.
I’ve tried ARGV.rewind, but got an ArgumentError “no stream to rewind”.
So, is there a method to swap to STDIN after reading all files? Thanks
in advance
I’ve started learning Ruby and trying to do the first (stupid) program
as exercise.
The input will be supported from a file and/or stdin.
If no file given, the program prompt user to insert all the data.
If a file is given, it expects line with at least two integers and will
read until the first bad line. After that, we expect another valid line.
If while reading the first sequence the file(s) end, a feature require
the user to insert some other data.
And there’s the problem!
Also if ARGV is empty, ARGF doesn’t swap to STDIN and gets continue to
return nil.
ARGF switches to $stdin only if ARGV is empty initially, i.e. when
the first read attempt is made.
I’ve tried ARGV.rewind, but got an ArgumentError “no stream to rewind”.
So, is there a method to swap to STDIN after reading all files? Thanks
in advance
You can push “-” onto ARGV which will make ARGF switch to STDIN - this
even works when you have read from ARGF already: