Ruby Arrays

Working with collections of data in Ruby

📚 What are Ruby Arrays?

Arrays are ordered collections that store multiple values in a single variable. Ruby arrays can hold different data types and provide powerful methods for manipulation. Arrays use zero-based indexing to access elements.


# Creating arrays
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", true, 3.14]

puts fruits[0]      # Output: apple
puts numbers.length # Output: 5
                                    

Array Operations

Adding Elements

Add items to arrays

arr = [1, 2]
arr.push(3)  # [1, 2, 3]

Removing Elements

Delete items from arrays

arr = [1, 2, 3]
arr.pop  # [1, 2]
🔍

Searching

Find elements in arrays

arr = [1, 2, 3]
arr.include?(2)  # true
🔄

Iteration

Loop through arrays

arr.each do |item|
  puts item
end

🔹 Creating Arrays

Ruby provides multiple ways to create arrays. You can use literal notation or the Array.new constructor.

# Array literal
fruits = ["apple", "banana", "orange"]
puts fruits.inspect  # Output: ["apple", "banana", "orange"]

# Empty array
empty = []
puts empty.inspect   # Output: []

# Array with numbers
numbers = [1, 2, 3, 4, 5]
puts numbers.inspect # Output: [1, 2, 3, 4, 5]

# Mixed data types
mixed = [1, "hello", true, 3.14]
puts mixed.inspect   # Output: [1, "hello", true, 3.14]

Output:

["apple", "banana", "orange"]
[]
[1, 2, 3, 4, 5]
[1, "hello", true, 3.14]

🔹 Accessing Array Elements

Access array elements using index numbers. Ruby uses zero-based indexing, and negative indices count from the end.

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

# Positive indexing (from start)
puts fruits[0]       # Output: apple
puts fruits[1]       # Output: banana
puts fruits[2]       # Output: orange

# Negative indexing (from end)
puts fruits[-1]      # Output: grape (last element)
puts fruits[-2]      # Output: orange (second to last)

# First and last methods
puts fruits.first    # Output: apple
puts fruits.last     # Output: grape

Output:

apple
banana
orange
grape
orange
apple
grape

🔹 Adding Elements

Add elements to arrays using push, <<, unshift, or insert methods. Each method adds elements at different positions.

fruits = ["apple", "banana"]

# Add to end
fruits.push("orange")
puts fruits.inspect  # Output: ["apple", "banana", "orange"]

# Using << operator
fruits << "grape"
puts fruits.inspect  # Output: ["apple", "banana", "orange", "grape"]

# Add to beginning
fruits.unshift("mango")
puts fruits.inspect  # Output: ["mango", "apple", "banana", "orange", "grape"]

# Insert at specific position
fruits.insert(2, "kiwi")
puts fruits.inspect  # Output: ["mango", "apple", "kiwi", "banana", "orange", "grape"]

Output:

["apple", "banana", "orange"]
["apple", "banana", "orange", "grape"]
["mango", "apple", "banana", "orange", "grape"]
["mango", "apple", "kiwi", "banana", "orange", "grape"]

🔹 Removing Elements

Remove elements from arrays using pop, shift, delete, or delete_at methods. Choose the method based on what you need to remove.

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

# Remove from end
last = fruits.pop
puts last            # Output: grape
puts fruits.inspect  # Output: ["apple", "banana", "orange"]

# Remove from beginning
first = fruits.shift
puts first           # Output: apple
puts fruits.inspect  # Output: ["banana", "orange"]

# Remove specific value
fruits = ["apple", "banana", "orange"]
fruits.delete("banana")
puts fruits.inspect  # Output: ["apple", "orange"]

# Remove by index
fruits.delete_at(0)
puts fruits.inspect  # Output: ["orange"]

Output:

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

🔹 Array Methods

Ruby provides many useful methods for working with arrays, including length, reverse, sort, and more.

numbers = [3, 1, 4, 1, 5, 9, 2, 6]

# Length/Size
puts numbers.length      # Output: 8
puts numbers.size        # Output: 8

# Reverse
puts numbers.reverse.inspect  # Output: [6, 2, 9, 5, 1, 4, 1, 3]

# Sort
puts numbers.sort.inspect     # Output: [1, 1, 2, 3, 4, 5, 6, 9]

# Unique values
puts numbers.uniq.inspect     # Output: [3, 1, 4, 5, 9, 2, 6]

# Check if empty
puts [].empty?           # Output: true
puts numbers.empty?      # Output: false

Output:

8
8
[6, 2, 9, 5, 1, 4, 1, 3]
[1, 1, 2, 3, 4, 5, 6, 9]
[3, 1, 4, 5, 9, 2, 6]
true
false

🔹 Iterating Through Arrays

Loop through array elements using each, map, or other iteration methods. These methods make processing collections easy.

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

# Using each
fruits.each do |fruit|
  puts fruit
end
# Output: apple, banana, orange

# Using each with index
fruits.each_with_index do |fruit, index|
  puts "#{index}: #{fruit}"
end
# Output: 0: apple, 1: banana, 2: orange

# Using map (transform elements)
uppercase = fruits.map { |fruit| fruit.upcase }
puts uppercase.inspect
# Output: ["APPLE", "BANANA", "ORANGE"]

Output:

apple
banana
orange
0: apple
1: banana
2: orange
["APPLE", "BANANA", "ORANGE"]

🔹 Searching Arrays

Find elements in arrays using include?, index, find, or select methods. These methods help locate specific values.

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

# Check if element exists
puts numbers.include?(3)     # Output: true
puts numbers.include?(10)    # Output: false

# Find index of element
puts numbers.index(3)        # Output: 2
puts numbers.index(10)       # Output: nil

# Find first matching element
result = numbers.find { |n| n > 3 }
puts result                  # Output: 4

# Select all matching elements
evens = numbers.select { |n| n.even? }
puts evens.inspect           # Output: [2, 4]

Output:

true
false
2
nil
4
[2, 4]

🔹 Array Slicing

Extract portions of arrays using range notation or slice methods. Slicing creates new arrays from existing ones.

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

# Range slicing
puts numbers[0..2].inspect    # Output: [1, 2, 3]
puts numbers[3..5].inspect    # Output: [4, 5, 6]
puts numbers[0...3].inspect   # Output: [1, 2, 3] (exclusive)

# Slice with start and length
puts numbers.slice(2, 3).inspect  # Output: [3, 4, 5]

# Negative indices
puts numbers[-3..-1].inspect  # Output: [6, 7, 8]

# First and last n elements
puts numbers.first(3).inspect # Output: [1, 2, 3]
puts numbers.last(2).inspect  # Output: [7, 8]

Output:

[1, 2, 3]
[4, 5, 6]
[1, 2, 3]
[3, 4, 5]
[6, 7, 8]
[1, 2, 3]
[7, 8]

🔹 Combining Arrays

Merge arrays using concatenation, union, or flatten methods. These operations create new arrays from multiple sources.

# Concatenation with +
arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
combined = arr1 + arr2
puts combined.inspect  # Output: [1, 2, 3, 4, 5, 6]

# Union (removes duplicates)
arr3 = [1, 2, 3]
arr4 = [3, 4, 5]
union = arr3 | arr4
puts union.inspect     # Output: [1, 2, 3, 4, 5]

# Flatten nested arrays
nested = [1, [2, 3], [4, [5, 6]]]
flat = nested.flatten
puts flat.inspect      # Output: [1, 2, 3, 4, 5, 6]

Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]

💡 Common Array Methods:

  • push/<<: Add to end
  • pop: Remove from end
  • unshift: Add to beginning
  • shift: Remove from beginning
  • length/size: Get array size
  • include?: Check if element exists
  • sort: Sort elements
  • reverse: Reverse order
  • each: Iterate through elements
  • map: Transform elements

🧠 Test Your Knowledge

What is the index of the first element in a Ruby array?