rubyguides

Array

Array.new, []

The Array class is Ruby’s primary ordered collection. Arrays can hold objects of any type and grow dynamically. They are one of the most frequently used data structures.

Creating Arrays

# Literal syntax
arr = [1, 2, 3]
arr = []  # Empty array

# With Array.new
arr = Array.new(3)        # => [nil, nil, nil]
arr = Array.new(3, 0)     # => [0, 0, 0]
arr = Array.new(3) { |i| i }  # => [0, 1, 2]

# From other objects
Array("hello")  # => ["hello"]
Array(1..5)     # => [1, 2, 3, 4, 5]

Accessing Elements

arr = [:a, :b, :c, :d]

arr[0]     # => :a (first)
arr[-1]    # => :d (last)
arr[1, 2]  # => [:b, :c] (slice)
arr.first  # => :a
arr.last   # => :d

Modification

arr = [1, 2, 3]

arr << 4        # => [1, 2, 3, 4] (push)
arr.push(5)     # => [1, 2, 3, 4, 5]
arr.pop         # => 5, arr is [1, 2, 3, 4]
arr.shift       # => 1, arr is [2, 3, 4]
arr.unshift(0)  # => [0, 1, 2, 3, 4]

Iteration

[1, 2, 3].each { |i| puts i }
[1, 2, 3].map { |i| i * 2 }     # => [2, 4, 6]
[1, 2, 3].select { |i| i > 1 } # => [2, 3]
[1, 2, 3].reduce(:+)            # => 6

Useful Methods

arr = [1, 2, 3, 2, 1]

arr.length      # => 5
arr.size        # => 5
arr.empty?      # => false
arr.include?(2) # => true
arr.index(2)    # => 1
arr.count(2)    # => 2
arr.uniq        # => [1, 2, 3]
arr.sort        # => [1, 1, 2, 2, 3]
arr.reverse     # => [1, 2, 3, 2, 1]

Practical Examples

Queue

queue = []
queue << item
item = queue.shift

Stack

stack = []
stack.push(item)
item = stack.pop

Set-like Operations

a = [1, 2, 3]
b = [2, 3, 4]

a | b   # => [1, 2, 3, 4] (union)
a & b   # => [2, 3] (intersection)
a - b   # => [1] (difference)

Matrix Representation

matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]

matrix[1][1]  # => 5 (center)

Comprehension-style

# Like list comprehension in Python
arr = (1..5).to_a.select { |x| x.even? }  # => [2, 4]
squares = (1..5).map { |x| x*x }           # => [1, 4, 9, 16, 25]

Arrays are versatile, efficient for indexed access, and form the foundation of many Ruby programs.

See Also