Learn to Program

Chapter 7

Flow Control


I like this chapter, it shows you what you need, but never formally introduces the concept of the counter. A counter is exactly what it sounds like, it's a variable whose soul purpose is to count, usually in increments of one, but it can be whatever you need.

Monkeys Jumping on the Bed

I chose this song because it isn't quite as long as 99 bottles of beer on the wall, but it still demonstrates the point of using a counter as both a counter and as a variable.

  1. #"Five Little Monkeys Jumping on the Bed" song lyrics

  2. counter = 5

  3. while counter != 1

  4. puts counter.to_s ' little monkeys jumping on the bed.'

  5. puts 'One fell off and bumped his head.'

  6. puts 'Called the doctor and the doctor said,'

  7. puts '"No more monkeys jumping on the bed."'

  8. puts 'No more monkeys jumping on the bed.'

  9. puts ''

  10. counter -= 1

  11. end

  12. puts counter.to_s ' little monkey jumping on the bed.'

  13. puts 'He fell off and bumped his head.'

  14. puts 'Called the doctor and the doctor said,'

  15. puts '"No more monkeys jumping on the bed."'

  16. puts 'No more monkeys jumping on the bed.'

  17. puts ''

  18. puts 'Now there\'s no little monkeys jumping on the bed.'

  19. puts 'None fell off and bumped their heads.'

  20. puts 'I called the doctor and the doctor said,'

  21. puts '"No more monkeys jumping on the bed."'

Result :

Annoying Teacher

This was the best I could do without completely giving the answer away.

  1. #Annoying teacher

  2. puts 'Your teacher asks the class, "In what year was I born?"'

  3. answer = gets.chomp

  4. response = 'I KNOW!'

  5. while answer != response

  6. puts 'Does anyone know the answer?'

  7. answer = gets.chomp

  8. end

  9. puts 'I was born in ' + (rand(30) + 1940).to_s + '.'

Annoying Teacher Extended

The counting the number of times a correct phrase is said is slightly harder. What we have to remember is to reset our counter if we fail to say the correct phrase every time.

  1. #Annoying teacher extended

  2. puts 'Your teacher asks the class, "In what year was I born?"'

  3. counter = 1

  4. answer = gets.chomp

  5. response = 'I KNOW!'

  6. while counter < 3

  7. puts 'Does anyone know the answer?'

  8. if answer == response

  9. counter += 1

  10. else

  11. counter = 1

  12. end

  13. answer = gets.chomp

  14. end

  15. puts 'I was born in ' + (rand(30) + 1940).to_s + '.'

Result:

I did my counter a little wierd because I didn't want to start at zero. But we'll get over that problem in the next chapter.