daremkd
daremkd

Reputation: 8424

Ruby: How do I get out of this loop

I have:

line = gets
while line = gets
   print line
end
puts 'out of loop'

How do I make line return nil?

Please note that on the second line line=gets is on purpose, so when gets=nil, line=nil and the whole condition becomes false.

Upvotes: 0

Views: 139

Answers (2)

Yu Hao
Yu Hao

Reputation: 122493

gets returns nil when it gets EOF (End of File).

You can send your terminal an EOF, this is done by pressing Ctrl-D on a Unix-like system. or Ctrl-Z on Windows.

Reference: IO#gets

Upvotes: 3

Chuck
Chuck

Reputation: 237110

If you mean "As somebody giving input from the command line, how would I make this terminate?": You would hit ctrl-D.

If you mean "How can I exit this loop programmatically?": Just check for whatever condition would terminate the loop and if it is true then break.

Upvotes: 2

Related Questions