Looping in Ruby

ruby, webdev, beginners, programming

4 minute read

03/16/2022

Looping in Ruby

An important and powerful concept to understand in any programming language is looping. By using loops we can iterate through arrays and interact with each piece of data in the array until a certain condition is met. If you know how to use loops in another language, like JavaScript, a few of the loops in Ruby will seem pretty familiar. Ruby has several ways to loop and iterate over data. I'll cover them and a few other concepts that may be useful in tandem with loops in this post.

For a more general overview of Ruby you can check out the article I wrote about getting started with ruby here

While Loop

While loops have three parts, the value to be incremented, a condition and an incrementer. Before starting your loop, initialize a variable to be incremented by the loop. Next set a condition for how long the loop should iterate based on the value of that variable. Then add the logic you want to execute for each value in the data set. Lastly increment the variable. In practice this looks something like this

def while_loop arr
i = 0
    
    while i < arr.length
        puts arr[i]
        i +=
    end

end

This loop will increment through each value of the array passed into it, printing each value to the terminal.

Until Loops

The until loop is like the opposite of a while loop. Instead of incrementing a variable while a condition hasn't been met, the until loop increments until a variable meets a condition. You'll still need a variable to increment, a condition and to increment the variable.

def until_loop arr
i = 0

    until i == arr.length
        puts arr[i]
        i +=
    end

end

The until loop may be easier to follow and read if you aren't already familiar with using the while loop. Instead of having to think of the loop doing something while something is true, you can think of the loop doing something until is true. Both loops do the same thing and can be used in place of one another, it's really up to what is easiest to follow. <br />

Looping with #times

Using <code>#times</code> is similar to using a for loop in other languages, just with a very simple syntax. All you need to loop with <code>#times</code> is the number of iterations you want to execute and what you want to do each time you iterate.

def using_times arr

    5.times do |i|
        puts arr[i]  
    end

end

This loop will iterate through the array 5 times, printing the values of each index to the terminal. Using blocks you can condense the previous method down to one line

def using_times(arr) 5.times { |i| puts arr[i-1] }

Looping with #each

Using <code>#each</code> is a great way to iterate over an entire list of data, like an array, or hash.

def using_each_arr arr

    arr.each { |i| puts arr[i]}

end

def using_each_hash hash

    hash.each { |key, value| puts key, value }

end    

Each is pretty straight-forward, it does one function for each item in a list. It doesn't have to have a condition making it dependent on the length of the whole list.

Looping with range

When using <code>#times</code> to iterate it starts counting from 0, using a range and <code>#each</code> allow us to start incrementing from a different number as well as put a set stop point on a loop using <code>#each</code>.

def using_range arr

    (4..15).each { |i| puts arr[i]}

The method <code>using_range</code> in the example above will allow us to start at 4 and go until 15. <br />

Using next in a loop

Using the <code>next</code> keyword in Ruby allows you to skip values in an array based on a condition. You can use <code>next</code> with any type of loop.

def using_next arr

    5.times do |i|
        next unless  i.odd?
        puts arr[i]  
    end    

end

This loop is almost the exact same as the previous example showing how to use do loops, the only difference is this loop skips all even indexed values. <br />

Stopping a loop early

By adding a break condition to a loop we can stop a loop early before the initial condition is met or before going over all the elements in a list. This will end the loop immediately.

def using_break arr

    arr.each do |i|
        break if i > 5
        puts arr[i]
    end

end    

Comparison to JavaScript

As you can see a lot of the loops available in Ruby are similar to Javascript with a different syntax. Personally I enjoy and prefer the ruby syntax, it's a lot simpler and much more straight forward to write.<br />

For example in Javascript to write a for loop we have to define a variable to increment, a condition and an action to execute at the end of the loop. This would look something like this

function forLoop(arr) {
    for (let i = 0; i < arr.length; i++) {
        console.log(arr[i])
    }
}

While in Ruby we could just write something like this

def do_loop arr

    arr.length.times do |i|
        puts arr[i]
        end

end

Ruby has a much simpler syntax, it also has methods like until that give the same result as other methods but with a syntax some may find more readable. In general a ruby loop will have less syntax needed to get the work done, as well as often times being more readable.

If you have any questions please leave a comment over on dev.to

Built with Next.js, Tailwind and Vercel