Common Array Methods in Ruby: A Comprehensive Overview

·

2 min read

An extensive list of array methods in Ruby along with code examples for each:

1. Adding and Removing Elements:

- << or push: Adds an element to the end of the array.

array = [1, 2, 3]

array << 4

array.push(5)

unshift: Adds an element to the beginning of the array.

array.unshift(0)

pop: Removes and returns the last element of the array.

last_element = array.pop

shift: Removes and returns the first element of the array.

first_element = array.shift

delete_at(index) : Deletes the element at the specified index.

array.delete_at(2)

2. Accessing Elements:

[]: Accesses an element at a specific index.

puts array[0] # Output: 1

first: Returns the first element of the array.

first_element = array.first

last: Returns the last element of the array.

last_element = array.last

3. Iterating Over Elements:

each: Executes a block for each element in the array.

array.each { |element| puts element }

- `map` or `collect`: Transforms each element of the array using a block.

new_array = array.map { |element| element * 2 }

select or filter: Returns an array containing elements for which the block returns true.

even_numbers = array.select { |element| element.even? }

reject:

Returns an array containing elements for which the block returns false.

odd_numbers = array.reject { |element| element.even? }

each_with_index: Iterates over each element with its index.

array.each_with_index { |element, index| puts "#{index}: #{element}"

4. Sorting and Reversing:

- sort: Returns a new array with elements sorted.

sorted_array = array.sort

reverse:

Returns a new array with elements in reverse order.

reversed_array = array.reverse

5. Checking and Searching:

include?: Checks if a certain element is included in the array

puts array.include?(3) # Output: true

index:

Returns the index of the first occurrence of a specified value.

index = array.index(2)

count: Returns the number of elements in the array.

count = array.count

- `empty?`: Checks if the array is empty.

puts array.empty? # Output: false

6. Transforming Arrays:

flatten:

Returns a new array that is a one-dimensional flattening of the original array.

nested_array = [[1, 2], [3, 4]]

flattened_array = nested_array.flatten

compact:

Returns a new array with nil values removed.

array_with_nil = [1, nil, 3, nil, 5]

compacted_array = array_with_nil.compact

7. Combining Arrays:

- `+`: Concatenates two arrays.

concatenated_array = array + [6, 7, 8]

- `concat`: Appends the elements of another array to the current array.

array.concat([6, 7, 8])

These examples demonstrate how to use various array methods in Ruby for different purposes.