No, this last post wasn't rejected but it is a compilation of some somewhat popular Ruby array methods hence why it comes last. But still they are worthy mentions so enjoy.
reject
This might be familiar already as the reject
method is used to remove elements from an Enumerable that do not satisfy a given condition. It returns a new array with the elements that were rejected by the condition in the block. This method does not modify the original array.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = numbers.reject { |num| num.odd? }
puts even_numbers
# Output: [2, 4, 6]
In the above code snippet, the reject
method is used to remove all odd numbers from the array. The condition in the block is num.odd?
, so all numbers that satisfy this condition (i.e., all odd numbers) are rejected, and the method returns a new array with the remaining elements (i.e., the even numbers).
grep_v
The grep_v
method is used to filter elements that do not match a specific pattern, typically a regular expression. It returns an array of elements that do not match the given pattern. This method is essentially the inverse of the grep
method, which returns elements that do match the pattern.
array = ["apple", "banana", "cherry", "date"]
non_fruits = array.grep_v(/a/)
# Output: ["cherry"]
In the above example, grep_v
is used to filter out elements that do not contain the letter 'a'. The returned array, non_fruits
, will therefore only include "cherry".
compact
The compact
method is used to remove nil values from an array. This method returns a new array that contains all the non-nil elements from the original array. The original array remains unchanged.
array = [1, 2, nil, 3, nil, 4]
array.compact
#Output: [1, 2, 3, 4]
In the above code snippet, the compact
method is called on an array that contains some nil values. The method returns a new array that contains only the non-nil values. The original array remains unchanged.
This brings our exposé of Ruby array methods to an end. I hope you enjoyed the ride.✌️✌️✌️
Top comments (0)