RFS: Loops and Iterators Part 1 - 014
Loops and Iterators will be an important part of being a programmer. In this episode we'll discover the various forms of loops and iterators in the ruby programming language.
Basic Iterators in Ruby
Let's begin with the most basic way to iterate. We can use the .times on an integer like so.
5.times do |x|
This will basically run 5 times outputting the value of x which starts at 0.
Another commonly used method is the .each iterator.
['dog', 'cat'].each do |animal|
We can also do for loops in ruby
for a in ['dog', 'cat'] do
Loops in Ruby
Let's take a look at some basic loops in ruby.
What we have above is what's called an infinite loop. This loop will run until someone terminates it. We can break out of a loop too.
puts "just once"
Infinite loops can be useful in many ways, for example a long running process like a server, server request are generally infinite loop listening for incoming requests and then responding with an answer. Games are also another example of infinite loops, where the variables in the loop change and in effect rendering out the frames based on the changes happening inside the loop.
A while loop will keep running based on certain conditions. So while something is true, stay in the loop. For example
something = 1
while something < 3 do
something += 1
The while loop will run until something is equal to 3 in that case the process will exit from the loop.
This is pretty self explanatory run the loop until some condition is true. Example
something_else = 1
until something_else == 10 do
something_else += 1
The loop above will run until something_else equals 10.
That's pretty much it for this episode if you want to see more examples check out the next episode!