Program giving wrong results

Asked by philguld over 1 year ago

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

  • timmay357 says

    I'm having the same problem and accidentally reposted the question ;p

  • enrique says

    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_number is set as an integer (42) and the result from ask is 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_s
    

    or change the guess to an integer

    guess.to_i == secret_number
    

    Changing the secret_number to a string will work in more situations (decimals, percents etc).

    Hope that helps.

  • enrique says

    Closed as answered, after 2 months.