How to Use Ruby’s Array Class (Examples + Useful Methods)

What’s an array?

An array is a built-in Ruby class, which holds a list of zero or more items, and includes methods that help you easily add, access, and loop over all these items.

This is helpful, because if arrays didn’t exist you would have to use many variables.

Example:

a = 1
b = 2
c = 3

But instead, you can do:

numbers = [1, 2, 3]

The best part?

You can put anything inside an array!

Like:

  • Numbers
  • Strings
  • More arrays! (that would make it a multi-dimensional array)

Let’s learn more about arrays so you can make the best use of them!

Contents

Arrays Are Zero-Indexed

You can access the elements inside an array using their index, which starts at 0.

If you had an array with the words “cat”, “dog” and “tiger” it would like this:

ruby array example

Here’s a code example that represents the data in the picture:

["cat", "dog", "tiger"]

Now:

You’ll discover what you can do with arrays!

Ruby Array Methods

Let’s start by learning how you can create an array.

You can create an empty array, then add new items into it, or you can create an array with starting values.

Initialize an empty array:

users = []

Initialize an array with data:

users = ["john", "david", "peter"]

If you’re creating a string-only array…

You can avoid having to type the quotes for every string by creating an array with %w.

Example:

users = %w(john david peter)

Now that we have an array you can access the elements it contains.

Here’s how:

users[0] # First element of the array
users[1] # Second element of the array
users[2] # Third element of the array

You can also use the first and last methods:

users.first # First element of the array
users.last  # Last element of the array

Here’s how to add items to your array:

# Both of these have the same effect, << is preferred.
users.push "andrew"
users << "andrew"

Here's how you delete elements from your array:

last_user = users.pop # Removes the last element from the array and returns it
user.delete_at(0)     # Removes the first element of the array

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

users.unshift "robert"  # Adds an element in front of the array
users.shift             # Removes the first element of the array and returns it

Does this array contain or include a certain item?

Check if a value exists in an array in Ruby:

numbers = [1,2,3]

numbers.include?(2)
# true

numbers.include?(10)
# false

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

words = ["cat", "coconut", "bacon"]
words.size

# 3

Here is a small cheatsheet for you:

Operation Methods
initialize Array.new, [], %w
read [0], first, last
add push, <<, unshift
remove pop, delete_at, shift

How to Convert An Array into a String

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

Here's an example:

letters = %w(a b c d)
letters.join

# "abcd"

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

letters = %w(a b c d)
letters.join(" ")

# "a b c d"

If you want the reverse operation, from string to array, you want to use the split method:

"a b c".split

Which results in:

["a", "b", "c"]

Multi-Dimensional Arrays (2D Arrays & More)

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

Example of 2d array:

users = [
 [1, 'Peter'],
 [2, 'Steven']
]

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

users[0][0]

# 1

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

users[0][1]

# 'Peter'

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:

users.flatten

# [1, "Peter", 2, "Steven"]

How to Iterate Over Ruby Arrays

Now that you have an array wouldn't it be nice if you could enumerate its contents and print them?

The good news is that you can!

Example: Print your array using each

users.each { |item| puts item }

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

users.each_with_index { |item, idx| puts "#{item} with index #{idx}" }

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.

users = users.map { |user| user.capitalize }
users = users.map(&:capitalize)

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 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:

numbers = [3, 7, 12, 2, 49]
numbers.select { |n| n > 10 }
# => 12, 49

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.

What Ruby will do is start from the end of the array. So -1 will get you the last item, -2 will get you second to last, etc.

Example:

letters = ["a", "b", "c"]

letters[-1]
# "c"

letters[-2]
# "b"

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.

numbers = numbers.sort

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.

numbers = [1, 3, 3, 5, 5]
numbers = numbers.uniq
# => [1, 3, 5]

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:

numbers.sample

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:

numbers.take(3)
numbers[0,3]

You can do more advanced Ruby array slicing. For example, you may want to get all the elements but the first one:

numbers[1..-1]

Notice the difference between using a comma (0,3) & a range (1..-1). The first one says "get me 3 elements starting at index 0", while the last one says "get me the characters in this range".

Get the size of an array:

numbers.size
# 5

Check if an array is empty:

numbers.empty?
# false

Remove nil values:

numbers << nil
# [1, 3, 3, 5, 5, nil]

numbers.compact
# [1, 3, 3, 5, 5]

Operations With Multiple Arrays

If you have two arrays and want to join or merge them into one you can do it like this:

# Faster, because this changes the users array
users.concat(new_users)  

# Slower, because this creates a new array
users += new_users       

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

users = users - users_to_delete

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

users & new_users

Conclusion

Ruby arrays are very useful and they will be a powerful ally by your side.

Make sure to practice creating an array, adding elements to it, accessing elements by index, etc. Also read about the Ruby hash, another important class which can be combined with arrays to write more interesting code.

Practice makes perfect!

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

10 thoughts on “How to Use Ruby’s Array Class (Examples + Useful Methods)”

  1. 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.

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

  3. 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!

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

Comments are closed.