ChatNoir
ChatNoir

Reputation: 545

Ruby, random number generator and if statement

After running this program, it only ever returns "miss"

What have I done wrong?

def method
print "Enter number from 0 to 4"
x = gets.chomp

num = rand(5)

if x == num
puts "hit"
else
puts "miss"
end
end

while 1==1
method
end

thanks

Upvotes: 0

Views: 426

Answers (2)

August
August

Reputation: 12558

gets.chomp results in a String. Comparing a String to a number with equality will never be true, because they are completely different types.

You should convert x to an integer before comparison, using String#to_i:

x = gets.chomp.to_i

Also, while 1==1 is a bit strange. This is more readable:

while true
  method
end

Or even better:

loop { method }

Upvotes: 4

ptierno
ptierno

Reputation: 10074

You are reading a string from $stdin:

Change

x = gets.chomp

to

x = gets.chomp.to_i

Hope this helps

Reference

String#to_i

Upvotes: 3

Related Questions