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.
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]
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"]
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]
Ruby provides numerous methods for working with arrays:
length
or size
: Returns the number of elementsempty?
: Checks if the array is emptyinclude?
: Checks if an element exists in the arraysort
: Returns a new sorted arrayreverse
: Returns a new array with elements in reverse orderRuby 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 }
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
each
or map
for iteration over for
loops.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.