apple
apple

Reputation: 35

(Ruby) Counting in Loops

could you help me out, please?

I want to write Ruby code in such a way that when I say the word "BYE!" 3 times in a row, it terminates the program.

My code is below

quotes = File.readlines('quotes.db')
puts = "What?"
print ">"
request = gets.chomp
while request != "BYE!"
  puts quotes[rand(quotes.length)]
  puts ">"
  request = gets.chomp
end

Any I could amend the code to follow the rules I want?

Upvotes: 0

Views: 78

Answers (3)

daremkd
daremkd

Reputation: 8424

puts 'If you type bye 3 times, this program will terminate'

bye_counter = 0
loop do
  input = gets.chomp
  if input == 'bye'
    bye_counter += 1
  else
    bye_counter = 0
  end

  break if bye_counter == 3
end

Upvotes: 0

spickermann
spickermann

Reputation: 106882

I would do something like this:

quotes = File.readlines('quotes.db')
counter = 0

puts 'What?'
loop do
  print '>'
  request = gets.chomp

  if request == 'BYE!'
    counter += 1
    break if counter >= 3
  else
    counter = 0
  end

  puts quotes.sample
end

Upvotes: 0

Abdul Baig
Abdul Baig

Reputation: 3721

Check if this is what you want. and tell me if any error occurs. this may be the rough code

quotes = File.readlines('quotes.db')
puts = "What?"
print ">"
counter = 0
request = gets.chomp
while counter < 3
  counter += 1 if request.eqls?("BYE!")
  puts quotes[rand(quotes.length)]
  puts ">"
  request = gets.chomp
end

Upvotes: 2

Related Questions