简体   繁体   中英

(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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM