user273072545345
user273072545345

Reputation: 1566

how to break a loop?

when 1
    add(first_number, second_number)

    begin 
    print "Calculate again? [y/n]: "
    response = gets.chomp

    if response.downcase =~ /[n]/
        break

    elsif response.downcase =~ /[^ny]/
        puts "please input y or n"

    else response.downcase =~ /[y]/
        puts "yay"
    end 
end 

EDIT

Profuse apologies. This is a changed version.

My question as it stands now is how do I keep repeating the question of 'please input y or n' when a user chooses to enter other than those characters?

Upvotes: 1

Views: 1428

Answers (3)

Gagan Gami
Gagan Gami

Reputation: 10251

the begin <code> end while <condition> is regretted by Ruby's author Matz. Instead, he suggests to use Kernel#loop,

e.g. The while statement modifier normally checks the condition before entering the loop. But if the while statement modifier is on a begin ... end statement, then it loops at least once. Same with the until statement modifier.

Example of while

val = 0
begin
   val += 1
   puts val
end while val % 6 != 0

Example of until

val = 0
begin
   val += 1
   puts val
end until val % 6 == 0

As you wants to know about breaks..

Example of break unless

val = 0
loop do
   val += 1
   puts val
   break unless val %6 != 0
end

Example of break if

val = 0
loop do
   val += 1
   puts val
   break if val %6 == 0
end

Output:

Above all four of these examples print the numbers 1, 2, 3, 4, 5, 6.

I hope this answer makes you clear..

For your reference I have found very nice Example of Code about Table of Contents You can Execute(Run) that code here online and check the result. If my answer somehow helps you then you can accept as answered. :)

Upvotes: 4

Stefan
Stefan

Reputation: 114248

I would probably extract the confirmation into a method, something like:

def confirm(message)
  loop do
    print "#{message} [y/n]: "
    case gets.chomp
    when 'y', 'Y' then
      return true
    when 'n', 'N'
      return false
    else
      puts 'please input y or n'
    end
  end
end

And use it like:

loop do
  puts 'Calculating...'
  sleep 5 # calculation
  puts '42'
  break unless confirm('Calculate again?')
end

Usage:

$ ruby test.rb
Calculating...
42
Calculate again? [y/n]: maybe
please input y or n
Calculate again? [y/n]: y
Calculating...
42
Calculate again? [y/n]: n
$

Upvotes: 2

Surinder ツ
Surinder ツ

Reputation: 1788

You should run your loopy method in a separate thread, and then kill that thread when the user presses any key on the keyboard ...

Upvotes: 0

Related Questions