Hello all, For example, if I run this program: secret_number = 42 guess = ask "Guess the number." if guess == secret_number alert "You win." else alert "You lose." end
If I run that and guess 42, it'll say I lose and as it should with every other number than 42.
3 responses
-
I'm having the same problem and accidentally reposted the question ;p
-
Hello philguld and welcome,
This is one of those bugs in the example programs that is being updated.
In short, it's the way that ruby compares types of variables and objects.
That is, the
secret_numberis set as an integer (42) and the result fromaskis a string or character, and when compared using == they are not the same .The string '42' is not the same as the number 42 even though to us they look the same,To make them comparable you need to change the secret_number to a string:
guess == secret_number.to_sor change the guess to an integer
guess.to_i == secret_numberChanging the secret_number to a string will work in more situations (decimals, percents etc).
Hope that helps.
-
Closed as answered, after 2 months.