Re: Deaf Grandma

if response == (response.upcase and “BYE”)

That doesn’t make sense. response.upcase is always true (not nil or
so (response.upcase and “BYE”) is just the same as “BYE”. Try it in irb
convince yourself.

There’s also no need to initialise response at the start of the program.
Apart from that your code looks fine. Here is an alternative version,
regular expressions and ‘next’ and ‘break’ flow control.

puts “Hey Sonny! It’s your lovely Grandmother! How are yeah?”

bye = 0
while response = gets
case response
when /^BYE$/
bye += 1
break if bye >= 3
puts “Hmmm… I would prefer…”
when /[a-z]/
puts “Huh?! I CAN’T HEAR YOU!”
when /[A-Z]/
puts “NO! NOT SINCE #{1930+rand(21)}!”
bye = 0

(The original problem didn’t say what to do if you said a blank line to
Granny, or a line which contained no alphabetic characters. In this
she just ignores you, but still resets the bye counter to zero. This is
to change.)

Note there is a subtlety with “gets”. If you ever modify this program to
take arguments on the command line, “gets” will behave strangely,
because it
will treat the command line arguments as filenames to read. For example,

ruby granny.rb 1930 1950

will try to read responses from files called “1930” and “1950”, instead
from stdin. To make sure you’re always using stdin, you’re better off

while response = $stdin.gets

(This magic Kernel#gets is a bit of ugliness inherited from Perl.
I find it trips me up rather than being helpful, which is why I mention
here :slight_smile:



P.S. At some point you may wish to rewrite this code in a way which can
easily be unit-tested - and which lets you talk to multiple grannies at
same time :slight_smile:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs