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.
#"Five Little Monkeys Jumping on the Bed" song lyrics
counter = 5
while counter != 1
puts counter.to_s ' little monkeys jumping on the bed.'
puts 'One fell off and bumped his head.'
puts 'Called the doctor and the doctor said,'
puts '"No more monkeys jumping on the bed."'
puts 'No more monkeys jumping on the bed.'
puts ''
counter -= 1
end
puts counter.to_s ' little monkey jumping on the bed.'
puts 'He fell off and bumped his head.'
puts 'Called the doctor and the doctor said,'
puts '"No more monkeys jumping on the bed."'
puts 'No more monkeys jumping on the bed.'
puts ''
puts 'Now there\'s no little monkeys jumping on the bed.'
puts 'None fell off and bumped their heads.'
puts 'I called the doctor and the doctor said,'
puts '"No more monkeys jumping on the bed."'
Result :
Annoying Teacher
This was the best I could do without completely giving the answer away.
#Annoying teacher
puts 'Your teacher asks the class, "In what year was I born?"'
answer = gets.chomp
response = 'I KNOW!'
while answer != response
puts 'Does anyone know the answer?'
answer = gets.chomp
end
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.
#Annoying teacher extended
puts 'Your teacher asks the class, "In what year was I born?"'
counter = 1
answer = gets.chomp
response = 'I KNOW!'
while counter < 3
puts 'Does anyone know the answer?'
if answer == response
counter += 1
else
counter = 1
end
answer = gets.chomp
end
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.