Start Coding

Topics

Ruby Arrays

Arrays are fundamental data structures in Ruby. They serve as ordered, integer-indexed collections of objects. Ruby arrays are dynamic, allowing you to store various data types in a single array.

Creating Arrays

There are multiple ways to create arrays in Ruby:


# Using square brackets
fruits = ["apple", "banana", "orange"]

# Using the Array.new method
numbers = Array.new(3, 0)  # Creates [0, 0, 0]

# Using %w for word arrays
colors = %w[red green blue]
    

Accessing Array Elements

Ruby arrays use zero-based indexing. You can access elements using square brackets:


fruits = ["apple", "banana", "orange"]
puts fruits[0]  # Output: apple
puts fruits[-1] # Output: orange (last element)

# Using ranges
puts fruits[0..1]  # Output: ["apple", "banana"]
    

Modifying Arrays

Arrays in Ruby are mutable. You can add, remove, or modify elements:


numbers = [1, 2, 3]
numbers.push(4)      # Adds 4 to the end: [1, 2, 3, 4]
numbers.unshift(0)   # Adds 0 to the beginning: [0, 1, 2, 3, 4]
numbers.pop          # Removes and returns the last element: 4
numbers.shift        # Removes and returns the first element: 0
numbers[1] = 5       # Replaces the second element: [1, 5, 3]
    

Common Array Methods

Ruby provides numerous methods for working with arrays:

  • length or size: Returns the number of elements
  • empty?: Checks if the array is empty
  • include?: Checks if an element exists in the array
  • sort: Returns a new sorted array
  • reverse: Returns a new array with elements in reverse order

Iterating Over Arrays

Ruby offers several ways to iterate over arrays:


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

# Using each
fruits.each { |fruit| puts fruit }

# Using each_with_index
fruits.each_with_index { |fruit, index| puts "#{index}: #{fruit}" }

# Using map to create a new array
uppercase_fruits = fruits.map { |fruit| fruit.upcase }
    

Multi-dimensional Arrays

Ruby supports nested arrays, allowing you to create multi-dimensional structures:


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

puts matrix[1][1]  # Output: 5
    

Best Practices

  • Use descriptive variable names for arrays to indicate their contents.
  • Prefer each or map for iteration over for loops.
  • Use Ruby Array Methods to simplify common operations.
  • Consider using Ruby Sets for unique collections of elements.

Arrays are versatile and powerful tools in Ruby programming. They integrate seamlessly with other Ruby features like Ruby Blocks and Ruby Each Iterator, making them essential for efficient data manipulation.