Good day, dear readers, coders, and enthusiasts! We have moved so far in Ruby that we can write pretty complex programs already. Now we have to learn repetitions and loops in Ruby.
It is a regular repetition operator that is present in almost all programming languages. It compares the condition given to it and if it returns "true", it performs the expressions within its block. Anytime when the condition returns "false", it breaks the repetition and sends you out of the block. Here is the syntax:
a_number = 0 while a_number < 10 puts "The number is = " + a_number.to_s a_number += 1 end
It is exactly the opposite of "while" operator. It resembles "unless" which is the opposite of regular "if". It repeats the block within it till the time until the condition returns "true".
a_number = 0 until a_number == 10 puts "The number is = " + a_number .to_s a_number += 1 end
You will find "break" useful if you want to stop the repetition somewhere in the process. Here is an example to this:
# If you are looking for the number 5 # then we have to stop it when the value of a number is 5 a_number = 0 while a_number < 100 break if a_number == 5 puts "We did not find the number 5 yet..." a_number += 1 end
In the example above, we break the repetition with the help of the "break" operator when we find the number 5.
If in some cases, you don't want to execute the block of code within the repetition and pass to the next iteration, the "next" operator comes in handy for this. In some other programming languages, you can meet the same operator, but called "continue".
a_number = 0 # if you want to output only odd numbers between 0-100 while a_number < 100 a_number+= 1 next if a_number% 2 == 0 puts a_number end # if the condition after the "next" operator returns "true" # then it does not execute the code coming after that and # goes to beginning, to the "while" operator.
Ruby also has many repetition and looping operators besides these. We will look at many of them when we write about the related topics, like Arrays, Hashes, Lists, Ranges. Some of those methods are “for” and “each”.
We came to an end of the "Ruby loops/repetitions" article. Wow, you have a pretty rich set of tools now. Every day, you learn a new set of tools and get more experienced. Your software also gets more professional and more productive.
Learning always lets you move forward. No matter who you are, how old you are.
Please write your feedback and comments. I will be glad to read them.
See you in the next article!