Ruby While Syntax

Is there a do ... while loop in Ruby?

CAUTION:

The begin <code> end while <condition> is rejected by Ruby's author Matz. Instead he suggests using Kernel#loop, e.g.

loop do 
# some code here
break if <condition>
end

Here's an email exchange in 23 Nov 2005 where Matz states:

|> Don't use it please.  I'm regretting this feature, and I'd like to
|> remove it in the future if it's possible.
|
|I'm surprised. What do you regret about it?

Because it's hard for users to tell

begin <code> end while <cond>

works differently from

<code> while <cond>

RosettaCode wiki has a similar story:

During November 2005, Yukihiro Matsumoto, the creator of Ruby, regretted this loop feature and suggested using Kernel#loop.

How can I write a while loop that checks for a Y or N character in Ruby?

There is an error in your logic. If answer is Y then obviously it's not equal to N, and so the condition of the loop is met.

You can fix this by using an 'and' in your condition:

(!answer.eql?("Y") && !answer.eql?("N"))

syntax error on while loop with ruby

I believe your error is being caused by your use of i++ which is not valid ruby syntax. Try replacing that with i += 1

Ruby : the while loop does not work

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.

Ruby while loop not stopping when condition is met

Because you are doing or on all of the parameters, so even if it matches first it will pass not matching the second.

Change your logic for while loop from variable != firstcondition or variable != secondcondition ...
to
!(variable == condition or variable == condition ... )



Related Topics



Leave a reply



Submit