Breaking the loop in case of EOF

  • Thread starter Marcin Górski
  • Start date
M

Marcin Górski

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

Thank you for your attention,
 
B

Brian Candler

Marcin said:
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).
 
R

Robert Klemme

2009/7/7 Brian Candler said:
gets will return nil in this case.

while str =3D STDIN.gets
=A0str.chomp!
=A0puts "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).

I believe a more idiomatic way would be

STDIN.each do |str|
str.chomp!
puts "String: #{str}"
end

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top