Page Content

Tutorials

Arrays In Ruby: An Ordered Collections With Integer Indexes

Arrays in Ruby

Arrays are ordered collections with integer indexes that can contain any kind of object in Ruby. In contrast to several other languages, Ruby arrays are changeable and untyped, which means that their elements can be altered at any moment and don’t have to all belong to the same class. Additionally, arrays can be resized dynamically, expanding in response to the addition or removal of elements.

Creating Arrays

Arrays can be created in Ruby in a number of ways:

Array Literals: Enclosing a list of object references with commas between them in square brackets [] is the most straightforward method.

%w and %W Syntax for String Arrays: A unique shorthand for arrays of strings without spaces is offered by Ruby. %w generates an array of strings that are space-delimited and do not require quotes around each string. Escape sequences and string substitutions are supported by %W.

Array.new Constructor: The array items can be initialised programmatically using this technique.

Accessing Elements

Indexes are used to number array elements, with zero being the initial index.

Positive Indexes: Use the array’s initial elements to access them.

Negative Indexes: With -1 as the final element, count from the end of the array.

Out-of-Bounds Access: Without raising an exception, Ruby returns nil if you try to read an element that is outside the array’s boundaries.

Subarrays (Slices): Two integers (start index and length) or a Range object can be used to extract specific parts of an array.

  • [start, length]: Returns length elements starting at start.
  • [range]: Returns elements identified by indexes in the given range. A two-dot range .. is inclusive of the end position, while a three-dot range ... excludes the end position.

Other Access Methods:

  • at(index): Equivalent to [] for a single index.
  • slice(index) or slice(start, length) or slice(range): Synonymous with []. slice! removes and returns the specified elements, modifying the array in place.
  • first, last: Return the first or last element, or n elements if an argument is given.
  • sample: Returns a random element or n random elements.
  • values_at: Extracts arbitrary values at specified indexes or ranges.

Multidimensional Array Access: You can use numerous sets of square brackets to access elements of nested arrays.

Manipulating Array Elements

Numerous operators and methods are available in Ruby to add, remove, and alter array contents.

Adding Elements:

  • << (shovel operator): adds a single object or several to the array’s end. Allowing for c chaining, it returns the array itself.
  • push(*objects): Similar to <<, it adds objects to the array’s end.
  • unshift(*objects): Items are added to the array’s beginning.
  • insert(index, *objects): Precedes the element at index with objects.
  • + (concatenation): Puts two arrays together to create a new array. It will raise an error if the right-hand side is not an array.
  • concat(other_array): The elements of other_array are appended to the receiver array’s end.

Removing Elements:

  • pop: Returns and eliminates the final piece.
  • shift: Removes the first element and gives it back.
  • delete(object): Removes every instance of a given item from the array.
  • delete_at(index): Eliminates the element located at a given index.
  • - (difference): Removes all elements from the right-hand array to create a new array.
  • slice!(index): Takes the element at the given index and puts it back.
  • slice!(start, length): Returns a new array after removing the length elements beginning at start.
  • slice!(range): Removes the range’s specified elements and returns a new array with them.

Updating Elements:

  • my_array[index] = value: Changes the element at the index. The array is expanded to that index with nil elements if the index exceeds the current size. An error occurs when an index is assigned before the array’s start.
  • my_array[start, length] = other_array: Replaces elements from other_array with a subarray.
  • my_array[range] = other_array: Replaces the components in a range.

Combining and Set Operations:

  • | (union): Combines two arrays, eliminates duplicates, and creates a new array. The sequence may not remain stable or consistent.
  • & (intersection): Returns a new array with duplicate-free elements that are shared by both arrays.
  • - (difference/subtraction): Contains entries from the first array that are absent from the second array in a new array.
  • uniq and uniq!: Alter the array in situ or return a new array with duplicate elements eliminated, respectively.

Repetition:

* (multiplication operator): Returns a new array after a predetermined number of iterations of the array’s contents. It uses a string as the argument when it calls the join method when multiplied by a string.

Iteration

Ruby prefers to use iterators containing code blocks over the more conventional for, while, or until loops for traversing data structures like arrays. Array contains the Enumerable module, which is the source of many array iteration techniques.

each: Makes a single call to the corresponding block for every array element.

map (or collect): Each element’s block is executed, and the return values are gathered into a new array.

select (or find_all): Includes entries for which the block returns true (any value other than false or nil) in a new array.

reject: Select’s opposite, return a new array containing the elements for which the block returns nil or false.

inject (or reduce): An all-purpose technique for distilling a single value from a collection. It continually applies the block using the current element and an accumulated value.

each_with_index: Provides the element in each iteration along with its index.

for loops: In Ruby, they are less idiomatic than iterators, even though they are supported. Iterating across enumerable objects, such as arrays, for loops assign elements to a loop variable.

while and until loops: Although less popular than block-based iterators, these are also supported for array iteration.

Multidimensional Arrays

Arrays with other arrays as their elements are known as multidimensional arrays in Ruby.

# Initializing a 2D array
my_2d_array = Array.new(3) { Array.new(3, 0) }

# Accessing a nested array element at row 2, column 2 (which holds the value 0)
puts my_2d_array[2][2] # => 0

Output

0

Flattening: One-dimensional arrays can be created from multi-dimensional arrays using the flatten function. You can define how many levels to flatten by using the flatten(n) function. Flatten! makes changes to the array in-place.

Splat Operator () with Arrays

Arrays can be unpacked and passed as separate arguments to methods or numerous parameters can be collected into an array using the splat operator (*).

Variable Number of Arguments: In method declarations, *parameter gathers all additional arguments into a specified array.

Coercing Arrays into Parameter Lists: *array is used in method calls to expand an array into separate arguments.

Decomposition: In the process of assigning, *variable gathers the leftover elements into an array.

Other Useful Array Methods and Concepts

Sorting: Sorted yields a new array. Sort! sorts in position c. It is possible to supply a block for custom sorting logic. If you want to sort by a certain criterion, sort_by is helpful.

Reversing: reverse returns a new reversed array. reverse! reverses in place.

Checking State: empty? returns true if the array contains no elements. length and size return the number of elements. nitems returns the number of non-nil elements.

Conversion: to_a converts an Enumerable object (like a Range or Hash) to an array. to_h converts an array of key-value pairs into a hash.

Casting to Array: The Array(arg) Kernel method can cast any object to an Array.

Arrays as Stacks and Queues: push and pop allow arrays to function as a last-in-first-out (LIFO) stack. shift and unshift allow arrays to function as a first-in-first-out (FIFO) queue.

join: Converts elements to strings and concatenates them, with an optional delimiter.

transpose: Swaps rows and columns of a nested array (matrix).

zip: Combines corresponding elements of multiple arrays into an array of arrays.

You can also read Numbers In Ruby: Integers, Floats, And More To Know

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index