How to execute a break in a loop via user input

T

Thomas Wilson

Hi all,

i am a complete noobie here to Ruby and programming in general.

I was looking for the best way to break a loop using "user input" via
gets.

I have a loop running that needs to be broken when the user hits a
specified key.

What would be the best way to go about this?

Thank your for your time and attention and sorry for such a "noobie"
question!

WPPK
 
R

Rajinder Yadav

Thomas said:
Hi all,

i am a complete noobie here to Ruby and programming in general.

I was looking for the best way to break a loop using "user input" via
gets.

I have a loop running that needs to be broken when the user hits a
specified key.

What would be the best way to go about this?

Thank your for your time and attention and sorry for such a "noobie"
question!

WPPK

There is no best way, here are 2 ways to mull over, first way gives you an idea
of how to break out of a loop. The 2ns way show use of a do/while loop, that
test for the loop condition is done at the end, not the start.

while(true)
c = gets
break if c.chomp == 'x'
end

or

begin
c = gets.chomp
end while c != 'x


--
Kind Regards,
Rajinder Yadav

http://DevMentor.org
Do Good ~ Share Freely
 
7

7stud --

Thomas said:
Hi all,

i am a complete noobie here to Ruby and programming in general.

I was looking for the best way to break a loop using "user input" via
gets.

I have a loop running that needs to be broken when the user hits a
specified key.

...and then hits return? Otherwise, you are getting into advanced
stuff.
 
B

Bertram Scharpf

Hi,

Am Mittwoch, 14. Okt 2009, 11:55:50 +0900 schrieb Rajinder Yadav:
There is no best way, here are 2 ways to mull over, first way gives you an
idea of how to break out of a loop. The 2ns way show use of a do/while
loop, that test for the loop condition is done at the end, not the start.

Be aware that pressing Ctrl-D (Unix) makes gets return nil, not a
string.
while(true)
c = gets
break if c.chomp == 'x'
end

loop do
c = gets
break if not c or c.chomp == 'x'
end
begin
c = gets.chomp
end while c != 'x

begin
c = gets.to_s.chomp
end while c != 'x

Bertram
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top