Reputation: 545
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
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
Reputation: 10074
You are reading a string from $stdin
:
Change
x = gets.chomp
to
x = gets.chomp.to_i
Hope this helps
Upvotes: 3