Adri
Adri

Reputation: 144

Ruby : the while loop does not work

I have a problem with my while loop. The loop displays directly from last puts without asking for the number that is to guess (adeviner).

adeviner = 4
a = 0

while adeviner != 4
  puts "Entrez votre chiffre"
  a = gets.chomp.to_i
end

puts "vous avez devine le chiffre"

Here is what the console returns:

ruby test.rb
vous avez devine le chiffre

I would like the console to ask me to type a number and tell me if that number is good or not.

Upvotes: 2

Views: 229

Answers (2)

chevybow
chevybow

Reputation: 11958

I think you are accidentally using the wrong variable in your loop

adeviner = 4
a = 0

while a!= adeviner
    puts "Entrez votre chiffre"
    a = gets.chomp.to_i
end

puts "vous avez devine le chiffre"

The code above uses the a variable in the loop. a is initally set to a default of 0 (which is not the number we are trying to guess) and the loop continues until the user correctly inputs "adeviner" value.

Upvotes: 1

Ursus
Ursus

Reputation: 30071

Your while block is executed while the condition is true but your condition is never true (4 != 4 is false)

Upvotes: 0

Related Questions