Ruby Loops for Beginners

What is a loop?

A loop is a piece of code that has a repetitive execution until a certain condition is met. Using loops allows you to

→ Go over a list of items and work with each element

→ When you want to repeat something many times

→ Keep a program running until the user wants to stop it at a certain point

The each loop

The Ruby method each lets you go over a list of items without keeping track of the number of iterations. This ruby method lets you do something until it goes through every single element in an array or hash. Here is an example:

“each” method in Ruby

In the above code, you can see that we are iterating over each element in the names array and prints that each person is cool. What happens under the hood is that the each method will use the block — { |n| puts "#{n} is cool"} once for every element in the array and pass every single element from the array into it and each of those elements will be represented by n variable that changes after each block execution. In this case the n is represented by a name from the array.

If you use the each method on a hash, you will need to use two parameters — one for the key and the other one for the value

The syntax will work as follows and you still need a block:

Give it a try in the examples above.

The times loop

The times loop is the easiest loop you will use in Ruby. It simply prints something the number of times you will tell it to. For example:

The while loop

The while loop is used in most programming languages and it’s useful to know. Here is an example of how a while loop is used:

To make the while loop to work, the components above are critical for its use

→ The number variable

→ The condition number < 10

→ The number +=1 to increase the number by 1

The variable number holds the value we are using for counting, the condition (number < 10) tells Ruby when to stop this loop (when the value of n is greater or equal to 10), and the number += 1 increases the counter to make progress.



Learning Ruby looping methods helps you keep your code clean and dry, imagine you had to do something 100 times? You would have to repeat your code when all you have to do is use Ruby’s useful looping to do the work for you in a few lines of code.

Hope this helps and I wish you happy coding:)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store