Exploring Arrays in Ruby

Lesson Overview

In today’s lesson, we’ll explore arrays in Ruby, a flexible and dynamic data structure. Arrays in Ruby allow modification of their elements and are central to Ruby programming due to their dynamic nature and ease of use. By the end of this lesson, you'll be able to create, manipulate, and understand the versatile applications of arrays in Ruby.

Understanding Arrays

In Ruby, arrays are ordered collections of objects, defined by enclosing elements in square brackets []. Each item within an array can be accessed through indexing, allowing for easy retrieval and modification of stored objects. This flexibility sets arrays apart from immutable collections.

["apple", "banana", "cherry"]
# Output: ["apple", "banana", "cherry"]

This example shows a simple array containing three elements.

In Ruby, arrays are dynamic, meaning they can grow or shrink in size as needed. Unlike arrays in some other languages, you don’t need to predefine their size, making them extremely flexible.

Creating Arrays

Arrays in Ruby are created by enclosing elements in square brackets [], separated by commas. Alternatively, you can use the Array class to initialize arrays or convert ranges to arrays.

  • Using square brackets [] is ideal for creating arrays with pre-defined elements, offering a concise syntax.
  • Array.new is used for creating empty arrays or specifying a fixed size with default values, providing more flexibility in initializing arrays.
packed_array = ["apple", "banana", "cherry"]
empty_array = Array.new
from_range = (1..3).to_a
puts packed_array.inspect  # Output: ["apple", "banana", "cherry"]
puts empty_array.inspect    # Output: []
puts from_range.inspect     # Output: [1, 2, 3]

This example demonstrates creating arrays directly, with the Array class, and by converting a range to an array.

Accessing and Modifying Arrays

Array elements are accessible by their index, with indexes starting at 0. Ruby also supports negative indexing (where -1 is the last element). Arrays can be sliced, and elements can be modified directly using their index positions.

my_array = ["apple", "banana", "cherry", "durian", "elderberry"]
puts my_array[1]         # Output: "banana"
puts my_array[-1]        # Output: "elderberry"
puts my_array[2, 2].inspect # Output: ["cherry", "durian"]
my_array[1] = "blueberry"
puts my_array.inspect    # Output: ["apple", "blueberry", "cherry", "durian", "elderberry"]

Here, we access elements by index, slice the array, and update an element.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal