Ruby Array 101: Primary Methods & How To Use Them
You have to make a choice. Choose...wisely.

Get occasional notifications about things like product discounts, blog posts, and new or updated tutorials. Unsubscribe at any time.

Gift Delivery Options
Quick Checkout
or Pay by Credit Card
Error processing your payment
  • You didn't choose whether or not to be added to the mailing list
Confirm
$0.00

Payments and credit card details are securely managed and protected by Learn Enough's payment processor, Stripe. More information on their site:

CART
Total
$0.00

Your Cart is Empty

$30
$300
$300
$XY
$XY
1234
Ruby Array 101: Primary Methods & How To Use Them

Ruby Array 101: Primary Methods & How To Use Them

Arrays, which are a common concept in coding, play an important role in every programming language. Arrays in Ruby are collections of elements that can belong to any data type, such as strings, integers, floats, etc.

You need to know how to work with Ruby arrays in order to write efficient and readable code. In this guide, you will learn the A to Z of the Ruby array, with coding samples and various resources to aid comprehension.

This article is suitable for both beginners just starting to learn Ruby arrays and experienced developers who want a quick recap on Ruby arrays.

Looking to learn Ruby on Rails development?👩‍💻🤔
Look no further, our courses will help you learn enough Ruby on Rails to be dangerous!

Definition of arrays

In the simplest terms, an array is a collection of elements. Different programming languages implement arrays in various ways.

However, one of the common features of arrays in every programming language is that array elements have integer indexes, and the index of the first element starts with 0.

This index is useful when you want to access array elements.

Programming languages like Java have fixed-size arrays. That means the array size is defined at the time of array declaration.

However, Ruby arrays are dynamic, allowing you to add or remove elements from the array as needed.

Also, most programming languages have arrays that can store only elements of one data type. Ruby is special, as Ruby arrays can hold values from different data types.

If you are interested in learning Ruby in depth, I encourage you to check out our comprehensive Learn Enough courses, including Learn Enough Ruby To Be Dangerous.

For a quick look at Ruby arrays in action, watch Jake Day Williams' video below.

Ruby array uses and applications

Key applications include:

  • Data Storage: Arrays can store a collection of data, be it numbers, strings, objects, or even other arrays. They provide a way to organize and manage data in a structured manner.

  • Iteration: Arrays, combined with loops, allow for iteration over a set of items, making it easier to process or manipulate each item in the collection.

  • Data Manipulation: With built-in methods, arrays in Ruby can be sorted, reversed, filtered, and transformed without the need for external libraries.

  • Stack and Queue Implementation: Using methods like 'push', 'pop', 'shift', and 'unshift', arrays can be used to implement other data structures like stacks and queues.

  • Searching and Filtering: Arrays provide methods to search for specific elements, filter out elements based on conditions, or even check for the existence of elements.

  • Logging and Reporting: Arrays are useful for generating logs and reports. An application could accumulate user activities in an array and later analyze the data to create insightful reports on user behavior.

  • Temporary Data Storage: Arrays can be used to temporarily store data that's being processed, such as user input, file data, or intermediate computation results.

  • Data Transformation: With methods like 'map', arrays can transform data, such as converting all strings in an array to uppercase or calculating the square of all numbers.

  • Multidimensional Data: Multidimensional arrays (arrays within arrays) are useful for representing complex data structures like matrices, tables, or grids.

  • Pattern Matching and Splitting: Arrays can be used in conjunction with regular expressions to split strings into arrays or to match patterns in data.

  • Combining Data: Arrays can be merged, concatenated, or combined in various ways to aggregate data from multiple sources.

  • Practical Applications:

    • E-commerce: Storing product listings, sorting products by price or rating, and filtering products based on user preferences.

    • Gaming: Storing high scores, player attributes, or game states.

    • Data Analysis: Storing datasets, filtering data, or performing statistical calculations.

    • Web Development: Storing form inputs, managing session data, or handling database query results.

Creating and accessing Ruby arrays

How to create an array in Ruby

While there are many ways to create arrays in Ruby, developers tend to choose two methods. One of them is using square brackets to create arrays and the other method is using Ruby's array class with the new() method. Let’s see how they work. 

Our first example shows how to create an integer array using square brackets. 

my_array = [1, 2, 3, 4, 5]

 print(my_array)

creating a ruby array 1

This is another example of using square brackets but this time we create an array of strings. 

fruits = ["apple", "banana", "orange", "grape"]

print(fruits)

create a ruby array 2

Let’s create a Ruby array that contains values from different data types. 

mixed_array = ["10", "hello", "true", "3.14", "b c"]

print(mixed_array)

creating a mixed ruby array

Remember, you can even include duplicate elements in Ruby arrays.

Using Array.new is as straightforward as using square brackets. When you use Array.new, you can specify both the size and the default value.

array = Array.new(size, default_value)

The 'size' informs Ruby about the number of elements your array should contain, while the 'default_value' determines the initial value for each of those elements.

The following examples demonstrate how to create arrays using the 'Array.new' method.

my_array = Array.new        

print(my_array)

new ruby array

This code simply makes an empty array. Nothing fancy, but sometimes that's just what you need.

my_array = Array.new(3)    

print(my_array)

make an empty ruby array

This creates an array with space for 3 elements, but we haven't given them any values yet.

my_array = Array.new(3, 0)

print(my_array)

3 element array

Here, we're making an array with 3 elements, and all of them are set to '0'.

Accessing array elements

You can access array elements using their indexes, which represent their positions in the array. Indexing begins at 0 and increments sequentially. If you want to access a specific element of the array, you should know the array index of that element.

To see how this works, let’s first create a string array. 

fruits = ["apple", "banana", "orange", "grape"]

accessing ruby array elements 1

The following table shows you the connection between indices and the items of the array. 

accessing array elements 2

You can access a specific element of an array in this way.

first_element = my_array[ i ]     → i is the index

Take a look at how the elements of the "fruits" array are accessed one at a time.

fruits = ["apple", "banana", "orange", "grape"]

first_element  = fruits[0]

second_element = fruits[1]

third_element  = fruits[2]

fourth_element = fruits[3]

puts(first_element)

puts(second_element)

puts(third_element)

puts(fourth_element)

accessing elements of ruby arrays

The above method forms part of what is known as array slicing. Slicing refers to accessing a specific range or segment of elements within an array, rather than individual elements. It allows you to extract a subset of elements based on specific indices or conditions.

For more on this, we've included two video tutorial snippets from Chapter 3 of our Learn Enough Ruby To Be Dangerous tutorial by Michael Hartl below, which visually walks you through the processes of array access and then advanced access via array slicing.

If you're wondering about the split method mentioned in the clip above, we'll cover that a little later in this article.

You can also access the range of elements as below, and negative indices start counting from the end, with -1 being the last element.

print(fruits[0..2])

puts("\n\n")

puts(fruits[-1])

access a range of ruby array elements

Using ‘at’ is another way to access a specific element. 

first_element = fruits.at(1)

print(first_element)

accessing specific ruby array elements

If we use the array[i] method to retrieve an element and the specified index is out of bounds, no error is returned.

print(fruits[100])

retrieve ruby array element

However, if you’re using the ‘fetch’ method, then it will raise an error.

print(fruits.fetch(100))

fetch a ruby array element

Additionally, there are other special methods that you can use to access elements. 

  • The ‘first’ and ‘last’ methods will return the last elements of an array.

  • The ‘take’ method will return the first n elements of an array.

  • The ‘drop’ method will return the elements after n elements of an array.

my_array = [1,2,3,4,5]

puts(my_array.first)

puts(my_array.last)

print(my_array.take(3))

puts

print(my_array.drop(3))

special ruby array methods

Modifying array elements

What if you want to replace an array element with a new value? Don’t worry; you can modify array elements by assigning new values to specific indexes.

The code below shows how to update the array's fifth entry.

my_array = [1,2,3,4,5]

print(my_array)

puts

print("Original fifth element = ",my_array[4])

puts puts

my_array[4] = 0

print("Updated fifth element=,my_array[4])

updating a ruby array element

If the array length is not pre-defined and the array is not full, elements can be added to the end of the array using ‘push'.

my_array = [1,2,3,4,5]

print("Original array:",my_array)

puts puts

my_array.push(6)

print("Updated array:",my_array)

updating a ruby array

You can also add a new element to the beginning of the array using ‘unshift'.

my_array = [1,2,3,4,5]

print("Original array:",my_array)

puts puts

my_array.unshift(0)

print("Updated array:",my_array)

updating a ruby array 2

Furthermore, using the ‘insert’ method, you can add a new element at any position of the array.

my_array = [1,2,3,4,5]

print("Original array:",my_array)

puts puts

my_array.insert(2, 2.5)

print("Updated array:",my_array)

ruby array insert method

You can use the same 'insert' method to add multiple elements as well. 

my_array = [1,2,3,4,5]

print("Original array:",my_array)

puts puts

my_array.insert(2, 2.5, 2.6, 2.7, 2.8, 2.9)

print("Updated array:",my_array)

ruby arrays multiple element insert

Voila! Now you know how to create an array, access its elements, and modify them.

However, if you want further clarification about array modifications, you need to Learn Enough Ruby To Be Dangerous.

Still searching for the Ruby on Rails grail?🏆👀
You’ve found it, in the acclaimed Ruby on Rails Tutorial, Learn Enough’s leading introduction to full-stack RoR development.

Splitting Ruby arrays

Before diving deeper into advanced Ruby array methods, you should understand the concept of array splitting. The 'split' method allows devs to break down a single array into multiple sub-arrays based on specific conditions or indices.

This operation is particularly useful when you need to segment data for further processing or analysis. Whether you're chunking data for batch processing or categorizing elements based on certain criteria, array splitting is a fundamental skill in Ruby programming.

To provide a clearer understanding of this concept, we've included a video tutorial snippet from Chapter 3 of our Learn Enough Ruby To Be Dangerous tutorial by Michael Hartl below, which walks you through the fairly simple process of array splitting in Ruby.

Primary methods in Ruby arrays

The magic of Ruby arrays doesn’t stop with creating and accessing Arrays. Ruby includes built-in methods for adding, removing, and manipulating array items. These make it easier to deal with Ruby arrays.

The push and pop methods

The ‘push’ method adds elements to the end of the array. For example, the following code adds '6' to the end of the array.

my_array = [1,2,3,4,5]

print("Original array:",my_array)

puts puts

my_array.push(6)

print("Updated array:",my_array)

ruby array push method

Conversely, the ‘pop’ method does the opposite by removing the last element and returning it. For example, the following code removes the last element (6) from ‘my_array’ and returns it using the 'pop' method.

my_array = [1,2,3,4,5]

print("Original array :",my_array)

puts puts

last_element = my_array.pop

print("Popped element :",last_element)

puts

print("Updated array :",my_array)

ruby array pop method

These two methods are very important when implementing stack or queue data structures using a Ruby array. In summary, the ‘push’ and ‘pop’ methods are crucial in managing arrays.

The shift and unshift methods 

The 'shift' method removes the first element from an array and returns it. For example, the following code removes the first element (1) and returns it.

my_array = [1,2,3,4,5]

print("Original array :",my_array)

puts puts

removed_element = my_array.shift

print("Removed element :",removed_element)

puts

print("Updated array :",my_array)

ruby array shift method

The 'unshift' element adds an element to the beginning of the array. For example, the following code adds the integer '0' to the beginning of the array.

my_array = [1,2,3,4,5]

print("Original array :",my_array

puts puts

my_array.unshift(0)

print("Updated array :",my_array)

ruby array unshift method

The length method 

When you want to know the number of elements in an array, the length method comes to your support. Check out this code which returns the number of elements in ‘my_array’.

my_array = [1,2,3,4,5]

print(my_array.length)

ruby array length method

The sort method 

The 'sort' method returns a new array with the elements sorted in ascending order. This does not affect the original array; rather, it returns a new array. For example, the following code returns a new array, which is a sorted array in ascending order of ‘my_array’.

my_array = [2,1,5,4,3]

print("Original array :",my_array)

puts puts

sorted_array = my_array.sort

print("Sorted array :",sorted_array)

ruby array sort method

The reverse method

The 'reverse' method returns a new array with all the elements in reverse order. This does not affect the original array. For example, the following code returns a new array, which is a reverse array of ‘my_array’.

my_array = [1,2,3,4,5]

print("Original array :",my_array)

puts puts

reversed_array = my_array.reverse

print("Reversed array :",reversed_array)

ruby array reverse method

The include method 

The ‘include’ method finds whether a given element is available in an array. If the element is present, then it’ll return 'true'; otherwise, it will return 'false'. For example, the following code checks whether the integer '3' is available in the ‘my_array’.

my_array = [1,2,3,4,5]

print("array :",my_array)

puts puts

if(my_array.include?(3))

    print("3 is present in the array")

else

    print("3 is not present in the array")

end

ruby array include method

Advanced Ruby array methods

In addition to primary methods, Ruby arrays have a set of advanced methods that make working with arrays much easier. These methods perform more complex operations on Ruby arrays.

The each method

The ‘each’ method iterates through an array to perform operations on each element of the array. It is an enumerator function that allows you to iterate over an array.

Syntax:

my_array.each { block }

For example, the following code will print each and every element of the ‘my_array’ in a new line.

my_array = [1,2,3,4,5]

print("Original array :",my_array)

puts puts

my_array.each{ |element| puts element }

ruby array each method

For more about array iteration, watch the following snippet from our tutorial.

The map method 

The ‘map’ method is similar to 'each', but it returns a new array with the results of the operation.  It’s an enumerator function that allows you to iterate over an array and returns an array. 

However, this does not affect the original array.

Syntax:

my_array.map { block }

Here is an example of using the 'map' method which returns the ‘new_array’ with each element of 'my_array' multiplied by 2.

my_array = [1,2,3,4,5]

print("Original array :",my_array)

puts puts

new_array = my_array.map{ |element| element * 2 }

print("New array :",new_array)

ruby array map method

The select method 

You can filter your array using the ’select’ method. The ‘select’ method returns a new array containing all elements for which the given block returns a true value. However, this does not affect the original array.

Syntax:

my_array.select { block }

For example, The following code will return an array called ‘new_array’ with all elements of 'my_array' that are greater than 2.

my_array = [1,2,3,4,5]

print("Original array :",my_array)

puts puts

new_array = my_array.select{ |element| element > 2 }

print("Filtered array :",new_array)

ruby array select method

The delete method

The ‘delete’ method removes all instances of a particular element from the array. For example, the following code removes all the instances of integer '2' from ‘my_array’ using the delete method.

my_array = [1,2,3,2,4,5]

print("Original array :",my_array)

puts puts

my_array.delete(2)

print("Updated array :",my_array)

ruby array delete method

Hooray! You've mastered advanced Ruby array techniques such as 'each', 'select', 'map', and 'delete'.

There are many things you can do with Ruby arrays. One of the best resources to unlock the full potential of arrays is the 'Learn Enough Ruby' tutorial.

Multidimensional arrays in Ruby 

So far, we’ve dealt with one-dimensional (regular) arrays. Now we are going to learn a more advanced concept called multi-dimensional arrays. 

These arrays go beyond the linear structure and can be thought of as arrays within nested arrays. 

Understanding multidimensional arrays

A multidimensional array, as its name suggests, is an array that holds more than one dimension. It introduces an added layer of complexity. A multidimensional array resembles a matrix in which each element contains values in two or more dimensions.

Multi-dimensional arrays in Ruby are initialized as nested layers of arrays – essentially, arrays within arrays. They prove especially useful when working with intricate data structures. 2D and 3D arrays are the most commonly encountered types of multidimensional arrays.

Creating and accessing multidimensional arrays

Creating a multi-dimensional array is similar to creating a regular array, except we need multiple indices instead of one. 

Much like regular arrays, we can create a multidimensional array either using square brackets or using the Array.new class method.

In the following example, you can see how to create a 2D array using the Array.new() method. 

arr2D = Array.new(2){Array.new(3)}

for i in 0..1

    for j in 0..2

        arr2D[i][j] = i*4+j

    end

end

arr2D.each do |row|

    puts row.join(' ')

end

accessing multidimensional ruby arrays

This is another example of creating a 2D array, but this time we use square brackets. 

arr2D = [[0,1,6],[2,3,8]]

arr2D.each do |row|

    puts row.join(' ')

end

creating a 2d ruby array

The two examples that you'll see next show you how to create 3D arrays using both the Array.new() method and square brackets.

arr3D = a = Array.new(2) { Array.new(3) { Array.new(4) } }

for i in 0..1

    for j in 0..2

        for k in 0..3

            arr3D[i][j][k] = k+1

        end

    end

end

arr3D.each do |layer|

    layer.each do |row|

        puts row.join(' ')

    end

    puts '-' * 10

end

3d ruby array method 1

arr3D =

[

 [[1,2,3,4],

  [1,2,3,4],

  [1,2,3,4]],

 [[1,2,3,4],

  [1,2,3,4],

  [1,2,3,4]],

]

arr3D.each do |layer|

    layer.each do |row|

        puts row.join(' ')

    end

    puts '-' * 10

end

3d ruby array method 2

To see multidimensional arrays in action, watch the video from Jake Day Williams, below.

Real-world examples of Ruby array methods

Let's dive into some hands-on examples of how Ruby array methods are applied in the real world.

Consider a simple Product class.

class Product

    attr_accessor :name, :category, :price

    def initialize(name, category, price)

      @name = name

      @category = category

      @price = price

    end

  End

Now, imagine we have an array of Product objects showcasing a range of items.

products = [

    Product.new("Smartphone", "Electronics", 500),

    Product.new("Sneakers", "Fashion", 100),

    Product.new("Laptop", "Electronics", 1200),

    # ... more products ...

  ]

Suppose there is a customer who wants to do the following things. 

Filter products by a category, say "Electronics"

electronics_products = products.select { |product| product.category == "Electronics" }

Find products within a particular price range, for instance, between $100 and $500.

affordable_products = products.select { |product| product.price.between?(100, 500) }

Eventually, he wants to showcase these filtered items.

  puts "Electronics Products:"

  puts electronics_products.map(&:name).join(", ")

  puts "\nAffordable Products:"

  puts affordable_products.map(&:name).join(", ")

Let’s see how the 'select' method and 'map' method behave in the above code samples. 

  • The select method: Let's start with 'select'. At its core, this method is your filter. It sifts through an array and picks out items based on conditions you set. It answers the question, "From this big list, which items meet my specific criteria?" So, every time you're looking to narrow down your list, the 'select' method is your go-to.

  • The map method: Moving on to the 'map' method. This method is all about transformation. Think of it as a craftsman reshaping raw materials. When you pass an array through a map, it takes each element and modifies it according to the instructions you give.

If you're starting to learn Ruby, you'll soon encounter Ruby on Rails. It's a very popular framework among Ruby developers. In that case, this Learn Enough article offers bright insight into the RoR development trends for 2024 and beyond.

aspiring ruby coder at work

In conclusion

Ruby arrays are a foundational concept with far-reaching practical applications. They enable efficient data handling, manipulation, and analysis across diverse scenarios. By understanding common Ruby array methods, you can write more efficient and effective code.

Learn Enough offers a great course to help you master Ruby programming. This course covers all aspects of Ruby, from the basics to more advanced topics. 

The "Learn Enough Ruby To Be Dangerous" course offers a practical and engaging approach to learning. It's fun, hands-on, and perfect for both newbies and those who've dabbled in Ruby before. 

For just $29 a month, you can access the full online tutorial, view streaming videos for each section, complete exercises with editable answers, track your progress, and become a member of the Learn Enough Society.

Why wait any longer? Sign up and Learn Enough Ruby To Be Dangerous today!

About Learn Enough! 📕💡
We offer carefully designed courses to take you from a beginner to a professional-grade Ruby on Rails developer.


Frequently asked questions 

What is an array in Ruby? 

An array in Ruby is an ordered, integer-indexed collection of objects, referred to as elements. Any object, such as an integer, number, hash, string, symbol, or even another array, can be an element in a Ruby array.

How do I create an array in Ruby? 

You can create an array in Ruby by declaring a variable and setting it equal to a list of elements within square brackets. For example, my_array = [1, 2, 3, 4, 5] creates an array of integers.

How do I access elements in a Ruby array?

Elements in a Ruby array can be accessed using their index. Array indices in Ruby start at 0, so the first element of an array can be accessed with my_array[0].

What are some common methods used with Ruby arrays?

Ruby arrays come with a host of built-in methods. Some of the most common ones include push and pop for adding and removing elements, length for getting the number of elements, sort and reverse for rearranging elements, and include? for checking if a specific element is present in the array.

What is a multidimensional array in Ruby?

A multidimensional array in Ruby is essentially an array that contains other arrays as its elements. These are particularly useful when dealing with complex data structures.

How can I learn more about Ruby arrays?

You can learn more about Ruby arrays through various online resources. One such resource is the "Learn Enough Ruby To Be Dangerous" course offered by Learn Enough. This course provides detailed explanations of array methods, along with exercises that allow you to apply what you've learned. You can access the course here.

Join the Mailing List

Get occasional notifications about things like product discounts, blog posts, and new or updated tutorials. Unsubscribe at any time.