Kevinvhengst Kevinvhengst - 1 year ago 64
Ruby Question

Ruby until always validates as false?

So I've written this piece of code to play around with numbers and the until loop:

number = rand(10)
puts number

puts "Guess the number"
guess = gets.chomp

until guess == number
puts "Guess again!"
guess = gets.chomp

puts "You've guessed it right! The number is #{guess}

But for some reason it it always stuck in the until loop and I am not sure why. I puts the random number to know that i guess right and try out the code. I'm completely new to Ruby, So I guess it's a very obvious thing I am missing, but I just dont see it.

From my point of view, whenever I prompt for the guess again, that guess that validated by the until loop with
until guess == number

Who can help me clear this up?

Answer Source

Instead of guess = gets.chomp(which will return a string of the user input), use guess = gets.to_i (which will convert user input into integer) to_i method will convert the element into integer and will drop /n character since it's not part of the integer. Don't need to add .chomp method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download