Share this post!

Mastering Ruby Arrays

Ruby arrays are a fundamental data structure that is used to store data in memory. Inside a Ruby array you can store anything you want, from strings to integers and even other arrays. The elements in a Ruby array are accessed using their index, which starts at 0.

This is what an array containing the words “cat”, “dog” and “tiger” would look like:

ruby arrays

And here’s is a Ruby array example that represents the data in the picture:

Ruby Arrays – Basic Operations

To work with an array you will have to create one first, there are multiple ways to do it.

Initialize an empty Ruby array:

Initialize an array with data:

Alternatively, you can avoid having to type the quotes for every string by creating a ruby array with %w:

Now that we have an array the next step would be accessing the elements that it contains.

Access array element by index:

You can also use the first and last methods:

At this point you may want to add items to your array:

And finally, here is how you delete elements from your array:

There is also the shift & unshift methods, which are similar to pop/push but take or add elements in front of the array.

Does this array contain or include a certain item? Check if a value exists in an array in Ruby:

What is the lenght of the array? (In other words, how many elements it contains)

Here is a small cheatsheet for you:

Negative Indexing

You learned that if you want to access a certain element from a Ruby array you need to use indexing (or methods like first & last).

But what about negative indexing?

I’m talking about using something like -1 as your array index. Well in that case what Ruby will do is to start from the end of the array. So -1 will get you the last item, -2 will get you second to last, etc.


Ruby Array to String

You can convert any array into a string by using the Array#join method.

Here’s an example:

Notice that this method takes 1 optional parameter so you can define a separator between the array elements when they are joined together.

Multidimensional Arrays

An array can be composed of other arrays, we call that a multi-dimensional array.

Example of 2d array:

To access the first element from the first sub-array you can use this syntax:

And for the second element of the first sub-array:

There are some cases where you want to convert a multi-dimensional array into a regular array.

You can do that using the flatten method:

Iterating Over Ruby Arrays

Now that you have an array wouldn’t it be nice if you could enumerate its contents and print them? Well the good news is that you can!

Example: Print your array using each

If you need to work with both the value and the index then you can use array’s each with index method:

Note: Most of these looping operations are available thanks to the Enumerable module, which is mixed into the Array class by default.

Example: Capitalize every word in your Array using map.

The map method doesn’t modify the array in-place, it just returns a new array with the modified elements, so we need to assign the results back to a variable. There is also a map! (notice the exclamation point) method which will modify the array directly, but in general the simpler version is preferred.

Another thing you may want to do is find all the items in your array that fit certain criteria.

Example: Find all the numbers greater than 10:

More Array Operations

There are a lot of things you can do using arrays, like sorting them or picking random elements.

You can use the sort method to sort an array, this will work fine if all you have is strings or numbers in your array. For more advanced sorting check out sort_by.

You can also remove the duplicate elements from an array, if you find yourself doing this often you may want to consider using a Set instead.

Notice that this doesn’t permanently change your array. Most Ruby methods will create a new array with the changes you requested. So if you want to save the results you need to use a variable or in this example, use the uniq! method.

If you want to pick one random element from your array you can use the sample method:

You may also want to “slice” your array, taking a portion of it instead of the whole thing.

Example: Take the first 3 elements from the array, without changing it:

Get the size of an array:

Check if an array is empty:

Remove nil values:

Operations involving multiple arrays

If you have two arrays and want to join them you can do it like this.

You can also remove elements from one array like this, where users_to_delete is also an array:

Finally, you can get the elements that appear in two arrays at the same time:


Ruby arrays are very useful and they will be a powerful ally by your side. Don’t forget to check out the documentation for the Array class if you are unsure of what a method does!

If you found this useful please share this post & subscribe to my newsletter below πŸ™‚

Dave Aronson says a couple of years ago

You’ve covered adding elements to the end of an array, and removing them from there, but ignored the front end, which is necessary in order to make a queue. There, you can use shift and unshift, respectively.

    Jesus Castello says a couple of years ago

    Thank you, I will add these πŸ™‚

    Jim OKelly says a couple of years ago

    Wait to you get into any?, none?, each_cons and each_slice πŸ™‚

    Isn’t ruby an awesome language? Great write up, keep them coming!

      Jesus Castello says a couple of years ago

      Yeah, I love Ruby! Thanks for your comment πŸ™‚

Thiago AraΓΊjo says a couple of years ago

You can also use Array#shift instead of Array#delete_at(0), and use Array#slice instead of Array#[start, length]

Rick Carlino says a couple of years ago

Another fun one is reaching around arrays in the opposite direction with negative indexes. Example:

%w(1 2 3 4 5 6)[-2]

=> returns “5”

Ruby arrays really do give you a lot out-of-the-box when you compare it to other languages. Nice post!

    Jesus Castello says a couple of years ago

    Thanks for your comment πŸ™‚

richard (@richardkmichael) says a couple of years ago

#each_with_index, #each_with_object and #zip, all from Enumerable, are often helpful with arrays. Most people seem unaware of #zip, in particular.

Igor Zhivilo says a couple of years ago

good post, didn’t know about ‘numbers.take 3’ method, thanks

Sanju says a couple of years ago

Nice Article πŸ™‚

Comments are closed