Breaking the loop in case of EOF

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,

Marcin Górski wrote:

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).

Thanks for your answers.

2009/7/7 Brian C. [email protected]:

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

On Tuesday 07 July 2009 13:23:51 Brian C. wrote:

while str = STDIN.gets
str.chomp!
puts “String: #{str}”
end

Which can also be written as:
STDIN.each_line do |str|

end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs