I'm just going to rewrite this, because there are a bunch of bad
things in it.
def ask(question)
response_is_valid = false
result = false
while !response_is_valid
puts question
reply = gets.chomp.downcase
case reply
when 'yes'
result = true
response_is_valid = true
when 'no'
result = false
response_is_valid = false
else
puts 'Please answer "yes" or "no".'
end
end
result
end
Part of the reason you're getting confused is that you're using the
'reply' variable for several things: to store the entered string, to
store the final result, and to determine whether a valid response has
been entered. That's called overloading a variable, and is bad
programming practice. In the version above (which is probably a bit
more verbose than it really needs to be, but should be easier for you
to work with), I've split those things out into three separate
variables.
Cheers,
Pete Yandell
http://9cays.com/
On 25/06/2006, at 11:32 PM, Dark Ambient wrote:
> I'm having a hard time with both getting my branching correct as well
> as my loop.
> In this little program, the survey taker asks expecting a "yes" or
> "no" (currently not working correctly). If any other response is
> given, then the survey taken says..please answer with yes or no...
>
> I commented out the return at the end since I'm not even sure what
> that's doing.
>
> TIA
> Stuart
>
> $stdout.sync = true
>
> def ask question
> reply = nil
> while (not reply)
> puts question
> reply = gets.chomp.downcase
>
> if (reply !='yes' || reply != 'no' )
> puts ' Please answer "yes" or "no".'
>
>
> elsif reply == 'yes'
> reply = true
> else reply == 'no'
> reply = false
> end
> end
> end
>
> #reply # This is what we return (true or false).
> #end
>