Removing values from strings in a while loop for Ruby
So I'm learning yet ANOTHER new language cause apparently my company thinks we should support every thing conceivable under the sun. Next week I suspect a memo about FORTRAN, automatonization, and punch cards. But that's neither her nor there. My question is, I'm running a loop (in this particular case a while loop) and have it collecting a string from the user. Name of pet. This while lo开发者_开发百科op continues to repeat until the user breaks it. However on the second time around I start receiving messages from Ruby telling me that the values have already been preassigned. It doesn't really cause issues as the program continues to run, but it doesn't look good.
Is there any way to clear the values so that it all returns to nil except the values I want, or would it be better to just put everything in functions so that there's no chance of regurgitation?
sample:
while moonies > 0
print "Would you like to punch a kitty? y or n"
y = gets()
if y = 'y'
print "Which kitty would you like to punch?"
slap = gets()
if slap == Tom
print "You spent 50 dollars punching a kitten."
....
else
print "Is there something else you'd like to kick or did you want to spend no money today?"
and so on and so on.
The problem is that when it gets back around to y is when the messages start to appear. thanks for the assistance.
Well...
if y = 'y'
is an assignment, not a comparison for equality. y='y' is always true. Should be
if y == "y\n" #note the newline, you got it from "gets"
if slap == Tom
This is a comparison, but Tom is a constant (it starts with a capital). I'm guessing you reassign a value to it, somewhere in your loop. Ruby complains about it. The newline issue will be here again. slap=gets.chomp will get rid of it.
精彩评论