Hi, I am confused why the following code requires “bye” 4 times? Is my
math wrong? The counter should start at 0, then increment three times:
to 1, 2, and finally 3.
(I’m a week 1 programming noob, so go gentle)
Cheers,
Tim.
Deaf grandma
bye = 0
puts “say something to grandma:”
input = gets.chomp
while bye < 3 #supposed to wait for 3 consecutive ‘buy’ entries to exit
the loop - seems to need 4 ‘bye’ entries!??
if input == “bye”
bye += 1
else bye = 0
end
if input == input.upcase
puts "no, not since " + (1930 + rand(21)).to_s + “!”
else
puts “huh!? SPEAK UP SONNY!”
end
input = gets.chomp
end
puts “bye bye”
Code trimmed down to the critical lines:
bye = 0
input = gets.chomp
while bye < 3
bye += 1
input = gets.chomp
end
You need to enter ‘bye’ four times because you need to enter something
once before the loop even starts.
bye = 0
gets
loop because bye < 3
bye = 1
gets
loop again because bye < 3
bye = 2
gets
loop again because bye < 3
bye = 3
gets
stop looping because bye == 3
Ahh, yes, I get it now. Thanks Dansei. It helps writing out what happens
in each loop like that; I’ll have to remember to do that.
I can see that I can either rewrite to start ‘bye = 1’ and ‘else bye =
1’, or change to ‘while bye < 2’. Both work, but would probably be
easier to document with the < 2 option. Something like:
while bye < 2 # waits for 3 consecutive ‘buy’ entries - has ‘< 2’
due to the initial gets before the while statement.
Thanks again for your time.
I would probably get rid of the first gets.chomp outside the loop and
move the gets.chomp inside the loop to the beginning of the loop. Like
this:
bye = 0
while bye < 3
input = gets.chomp
if input == input.upcase # needs to be all upcase
...
elsif input.downcase == "bye" # bye, Bye, BYe etc.
...
end
end
I see, it’s easier to read/cleaner that way too. It’s all starting to
drop into place in my understanding.
Thanks again.