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|  puts xend# output012345

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|  puts animalend# outputdogcat

We can also do for loops in ruby

for a in ['dog', 'cat'] do  puts aend# outputdogcat

Loops in Ruby

Let's take a look at some basic loops in ruby.

loop do  puts "infinitely"end

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.

loop do  puts "just once"  breakend

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.

While Loop

A while loop will keep running based on certain conditions. So while something is true, stay in the loop. For example

something = 1while something < 3 do  puts "while"  something += 1end

The while loop will run until something is equal to 3 in that case the process will exit from the loop.

Until Loop

This is pretty self explanatory run the loop until some condition is true. Example

something_else = 1until something_else == 10 do  puts "until"  something_else += 1end

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!