Ruby Logo

Ruby Arrays

Deep dive into Ruby arrays - creation, manipulation, and powerful array methods.

Home Ruby Ruby Arrays

Ruby Arrays Mastery

Arrays are ordered collections of objects in Ruby. They're one of the most versatile and frequently used data structures, capable of storing any mix of data types and providing powerful methods for manipulation.

Creating Arrays

Ruby provides several ways to create arrays, from simple literal syntax to more advanced techniques.

# Array literal syntax
numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]
mixed = ["hello", 42, true, :symbol]
empty = []
# Using Array.new
zeros = Array.new(5, 0) # [0, 0, 0, 0, 0]
letters = Array.new(3) { |i| ('a'.ord + i).chr } # ["a", "b", "c"]
# String to array conversion
"hello".chars # ["h", "e", "l", "l", "o"]
"apple,banana,cherry".split(",") # ["apple", "banana", "cherry"]
# Range to array
(1..5).to_a # [1, 2, 3, 4, 5]
('a'..'e').to_a # ["a", "b", "c", "d", "e"]

Accessing Elements

Ruby arrays use zero-based indexing and provide flexible ways to access elements.

# Basic indexing (zero-based)
fruits = ["apple", "banana", "cherry", "date"]
puts fruits[0] # "apple" (first element)
puts fruits[2] # "cherry" (third element)
# Negative indexing (from end)
puts fruits[-1] # "date" (last element)
puts fruits[-2] # "cherry" (second to last)
# Method-based access
puts fruits.first # "apple"
puts fruits.last # "date"
puts fruits.at(1) # "banana"
puts fruits.fetch(10, "not found") # "not found" (safe access)
# Slice/range access
puts fruits[1, 2] # ["banana", "cherry"] (start at index 1, take 2)
puts fruits[1..3] # ["banana", "cherry", "date"] (inclusive range)
puts fruits[1...3] # ["banana", "cherry"] (exclusive range)

Adding & Removing Elements

Ruby arrays are dynamic - you can easily add or remove elements from any position.

# Adding elements
numbers = [1, 2, 3]
numbers.push(4) # Add to end: [1, 2, 3, 4]
numbers << 5 # Shorthand for push: [1, 2, 3, 4, 5]
numbers.unshift(0) # Add to beginning: [0, 1, 2, 3, 4, 5]
numbers.insert(2, 1.5) # Insert at index 2: [0, 1, 1.5, 2, 3, 4, 5]
# Removing elements
last = numbers.pop # Remove and return last: 5
first = numbers.shift # Remove and return first: 0
removed = numbers.delete_at(1) # Remove at index 1: 1.5
numbers.delete(3) # Remove all instances of 3
# Bulk operations
numbers.concat([10, 11, 12]) # Add multiple elements
numbers += [13, 14] # Array concatenation
numbers.clear # Remove all elements

Essential Array Methods

Ruby arrays come with powerful built-in methods for transformation, filtering, and analysis.

# Transformation methods
numbers = [1, 2, 3, 4, 5]
squared = numbers.map { |n| n ** 2 } # [1, 4, 9, 16, 25]
doubled = numbers.collect { |n| n * 2 } # [2, 4, 6, 8, 10] (alias for map)
# Filtering methods
evens = numbers.select { |n| n.even? } # [2, 4]
odds = numbers.reject { |n| n.even? } # [1, 3, 5]
big_numbers = numbers.filter { |n| n > 3 } # [4, 5] (alias for select)
# Aggregation methods
sum = numbers.reduce(0) { |acc, n| acc + n } # 15
sum = numbers.sum # 15 (Ruby 2.4+)
product = numbers.reduce(:*) # 120 (1*2*3*4*5)
max = numbers.max # 5
min = numbers.min # 1
# Search methods
found = numbers.find { |n| n > 3 } # 4 (first match)
includes = numbers.include?(3) # true
index = numbers.index(3) # 2
all_positive = numbers.all? { |n| n > 0 } # true
any_big = numbers.any? { |n| n > 10 } # false

Sorting & Ordering

# Basic sorting
letters = ["c", "a", "b", "d"]
sorted = letters.sort # ["a", "b", "c", "d"] (new array)
letters.sort! # Sort in place (mutating)
# Custom sorting
numbers = [5, 2, 8, 1, 9]
desc = numbers.sort { |a, b| b <=> a } # [9, 8, 5, 2, 1] (descending)
desc = numbers.sort.reverse # Alternative way
# Sort by criteria
words = ["apple", "pie", "banana"]
by_length = words.sort_by(&:length) # ["pie", "apple", "banana"]
by_length = words.sort_by { |word| word.length } # Same result
# Other ordering
numbers.shuffle # Randomize order
numbers.reverse # Reverse current order

Iteration Patterns

# Basic iteration
fruits = ["apple", "banana", "cherry"]
fruits.each { |fruit| puts fruit }
# Iteration with index
fruits.each_with_index do |fruit, index|
puts "#{index}: #{fruit}"
end
# Iteration with object
fruits.each_with_object({}) do |fruit, hash|
hash[fruit] = fruit.length
end
# {"apple"=>5, "banana"=>6, "cherry"=>6}
# Times iterator for arrays
result = []
5.times { |i| result << i ** 2 }
puts result # [0, 1, 4, 9, 16]

Performance Tip: Use each when you don't need a new array, map when transforming, and select/reject when filtering.

Multi-dimensional Arrays

# 2D Array (Matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Accessing 2D elements
puts matrix[0][1] # 2 (row 0, column 1)
puts matrix[2][2] # 9 (row 2, column 2)
# Iterating 2D arrays
matrix.each_with_index do |row, row_index|
row.each_with_index do |cell, col_index|
puts "[#{row_index}][#{col_index}] = #{cell}"
end
end
# Flattening multidimensional arrays
flat = matrix.flatten # [1, 2, 3, 4, 5, 6, 7, 8, 9]

Performance Best Practices

✅ Efficient Operations

  • Use << instead of += for single elements
  • Prefer each over for loops
  • Use frozen_string_literal for string arrays
  • Chain methods instead of multiple iterations

❌ Avoid These

  • Repeatedly calling array + [element]
  • Using delete in loops (use reject)
  • Unnecessary flatten calls
  • Modifying arrays during iteration

Array Mastery Checklist

  • Creation: Know literal syntax, Array.new, and conversion methods
  • Access: Use indexing, negative indices, slicing, and safe methods
  • Modification: Add/remove elements with push, pop, shift, unshift
  • Transformation: Master map, select, reject, and reduce
  • Iteration: Use appropriate methods for your needs (each, map, etc.)
  • Sorting: Sort, sort_by, and reverse operations
  • Advanced: Handle multi-dimensional arrays and chaining

Quick Navigation

Related Topics

Video Tutorial

Watch and learn ruby arrays

Pro Tip: After reading through the content above, watch this video to reinforce your understanding and see the concepts in action!