The following is the code for a basic while loop:
i = 0 while i < 10 puts "Hey there" i += 1 end
Let's walk through the steps for building a while loop in Ruby:
- We have to create a variable that will work as a counter and set it equal to 0.
- Then we declare the conditional which you can read as: while i is less than 10, continue looping.
- Inside the loop, we place the code we want to be executed each time the loop runs.
- We increment our i loop variable by 1 with each iteration. This is required to prevent an infinite loop from occurring. An infinite loop is what happens when you forget to tell the loop when it can stop and it will eventually crash the program.
- Lastly, we supply the end keyword to designate where ...