Ruby

Iterate Through an Array in Ruby

Ruby is a powerful programming language that seems to embrace the concept of easy to learn and use heavily. When it comes to performing almost fundamental tasks in Ruby, chances are there is a built-in method for it.

This tutorial will discuss various ways you can iterate over the items in a Ruby array.

Creating an Array

In Ruby, we can create an array by adding a list of comma-separated values inside a pair of square brackets. Each item in the array is known as an element and can be of any Ruby type.

myarray = [1,2,3.9, "hello", "world", [], {}]

The above example shows a simple array comprising of various element types such as integers, floats, strings, arrays, hashes, and more.

In some instances, you may have an array made up of string type only. In that case, you can create and enclose the values in %w{}

Example:

databases = %w{MySQL, PostgreSQL, Redis, Memcached, MongoDB, Elasticsearch}

If we use the above syntax to create an array, Ruby will separate the values by whitespaces and create individual elements, as shown below:

print databases
["MySQL,", "PostgreSQL,", "Redis,", "Memcached,", "MongoDB,", "Elasticsearch"]

Iterating Over an Array

Iterating over an array and working with individual elements is a fundamental programming concept. Ruby provides us with a few methods to perform such a task.

Using each method

The Ruby Enumerable#each method is the most simplistic and popular way to iterate individual items in an array.

It accepts two arguments: the first being an enumerable list, and the second being a block. It takes each element in the provided list and executes the block, taking the current item as a parameter.

Here is an example:

databases = %w{MySQL, PostgreSQL, Redis, Memcached, MongoDB, Elasticsearch}
databases.each do |i|
    puts i
end

The above simple example illustrates how the method works. It takes each item in the databases array and runs a block with the current item. In our example, the block is a simple puts method.

The resulting output is each element in the array as:

$ ruby iterator.rb
MySQL,
…,
MongoDB,
Elasticsearch

Using each_with_index method

In some cases, we may want to print the element and its position index in the array. To do this, we can use the each_with_index method

It works like each method but returns both items and their index positions as:

databases = %w{MySQL, PostgreSQL, Redis, Memcached, MongoDB, Elasticsearch}
databases.each_with_index do |element, index|
    puts "#{index} => #{element}"
end

In the example above, Ruby will return each element in the array mapped to its index as shown:

0 => MySQL,
1 => PostgreSQL,
…,
5 => Elasticsearch

Using a for Loop

Like in most programming languages, you can also iterate over the elements in an array by using a for loop.

databases = %w{MySQL, PostgreSQL, Redis, Memcached, MongoDB, Elasticsearch}
for element in databases
    puts element
end

The above example works like each method and returns individual elements in the array.

Using select

Ruby also has another method for iterating over items in an array: the select method. The select method works as shown in the example below

databases = %w{MySQL, PostgreSQL, Redis, Memcached, MongoDB, Elasticsearch}
databases.select do |i|
    puts i
end

The select method is useful when you want a subset that meets specific criteria. For example, select only even values in an array as shown:

nums = [1,20, 23, 28, 2, 100, 34, 53, 22, 21, 11]
nums.select do |i|
    i.even?
end

The above example should return only a subset of the nums array where the element is even.

=> [20, 28, 2, 100, 34, 22]

Using map

The map method is another way to iterate over the items in an array. The functionality works similarly to any array iterator in Ruby. However, it is mainly useful when you want to transform the array.

nums = [1,20, 23, 28, 2, 100, 34, 53, 22, 21, 11]
nums.map do |i|
    i * 3
end

The example above will return a new object with the items in the array multiplied by 3.

If you want to affect the original array, you can use the map! method.

nums = [1,20, 23, 28, 2, 100, 34, 53, 22, 21, 11]
nums.map! do |i|
    i * 3
end
print nums
[3, 60, 69, 84, 6, 300, 102, 159, 66, 63, 33]

In the example above, the map! Method alters the source array and creates an array with the specified modifications.

Conclusion

This guide discussed how to iterate over items in an array using for loops and other built-in Ruby methods.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list