RubyUser
RubyUser

Reputation: 29

While loops in Ruby

I want to exit only after I say 'BYE' three consecutive times. It is about a deaf grandma who will only hear things if the letters are all in caps.

I tried having three different variables, but that did not work. My code is below and it works when I say 'BYE' only once.

whatSaid = 'Hi!'

while (whatSaid != 'BYE')
  whatSaid = gets.chomp
  if (whatSaid == 'BYE')
    puts 'FINE! LEAVE YOUR POOR GRANDMA TO DIE.'
  else
    if (whatSaid == whatSaid.upcase)
    puts 'NO, NOT SINCE ' + rand(1930...1951).to_s + '!'
    else
    puts 'HUH!? SPEAK UP, SONNY!'
    end
  end
end

Upvotes: 0

Views: 66

Answers (1)

Taryn East
Taryn East

Reputation: 27747

why not a variable called bye_count - start it out at 0 and increment it each time you hear 'BYE' - and when that gets to 3, exit

eg

what_said = 'Hi!'
bye_count = 0

while (bye_count < 3)
  what_said = gets.chomp
  if (what_said == 'BYE')
    bye_count += 1
    puts 'FINE! LEAVE YOUR POOR GRANDMA TO DIE.'
  else
    if (what_said == what_said.upcase)
      puts 'NO, NOT SINCE ' + rand(1930...1951).to_s + '!'
    else
      puts 'HUH!? SPEAK UP, SONNY!'
    end
  end
end

Unrelated note: ruby generally uses underscore_case for variable names, rather than camelCase :)

Upvotes: 1

Related Questions