DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Kade Esterline
Kade Esterline

Posted on • Updated on

Looping in Ruby

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Looping with #times

Using #times is similar to using a for loop in other languages, just with a very simple syntax. All you need to loop with #times 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
Enter fullscreen mode Exit fullscreen mode

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] }
Enter fullscreen mode Exit fullscreen mode

Looping with #each

Using #each 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    
Enter fullscreen mode Exit fullscreen mode

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 #times to iterate it starts counting from 0, using a range and #each allow us to start incrementing from a different number as well as put a set stop point on a loop using #each.

def using_range arr

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

Enter fullscreen mode Exit fullscreen mode

The method using_range in the example above will allow us to start at 4 and go until 15.

Using next in a loop

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

def using_next arr

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

end
Enter fullscreen mode Exit fullscreen mode

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.

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    
Enter fullscreen mode Exit fullscreen mode

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.

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])
    }
}
Enter fullscreen mode Exit fullscreen mode

While in Ruby we could just write something like this

def do_loop arr

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

end
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
kaleb_franken profile image
Kaleb Franken

Saving this for later!

🌚 Life is too short to browse without dark mode