Benji
Benji

Reputation: 35

Not sure why this is happening

I wrote this code:

print "100 + 1 ="
user_answer = gets.chomp
if user_answer == 101
  puts "That's correct"
else
  puts "Sorry, you're wrong"
end

When I run this code, no matter what my answer is, the else branch is executed. If someone could point me in the correct direction it'd be greatly appreciated.

Upvotes: 2

Views: 57

Answers (2)

falsetru
falsetru

Reputation: 369074

user_answer is a string:

user_answer = "101\n".chomp
# => "101"

The code is comparing a string and an number, which returns always false:

user_answer == 101
# => false

You need to convert the string to number, or compare it with a string:

user_answer.to_i == 101
# => true
user_answer == "101"
# => true

Upvotes: 4

user513951
user513951

Reputation: 13622

You need to cast user_answer as a number before comparing it to 101.

if user_answer.to_i == 101
  ...

Upvotes: 1

Related Questions