Hello,
I need to break a loop when program gets an EOF from STDIN. For example
in C++ I would do it by following way:
while(1) {
if((cin >> a).eof()) break;
}
I don’t know how do it in Ruby. I tried the idea, but it doesn’t work
well:
irb(main):007:0> loop do
irb(main):008:1* str = gets.chomp
irb(main):009:1> break if STDIN.eof?
irb(main):010:1> puts "String: " + str
irb(main):011:1> end
hey
joe
String: hey
hey
String: joe
hey
String: hey
=> nil
I need to break a loop when program gets an EOF from STDIN.
gets will return nil in this case.
while str = STDIN.gets
str.chomp!
puts “String: #{str}”
end
Beware that “STDIN.gets” is subtly different from a bare “gets”. The
first always reads from STDIN. The second will read from the files named
on the command line if the command line is not empty. (See also ARGF).
Beware that “STDIN.gets” is subtly different from a bare “gets”. The
first always reads from STDIN. The second will read from the files named
on the command line if the command line is not empty. (See also ARGF).
I believe a more idiomatic way would be
STDIN.each do |str|
str.chomp!
puts “String: #{str}”
end