Extract! method in Rails - 6


Extract! method in Rails - 6


Rails - 6 adds extract! method for array.

extract! method removes and return the elements for which the block returns a true value. If no block is given an Enumerator is returned instead.

Now, you may be wondering we can use reject! or select! similar to what we thought of earlier. This might seem tricky at the first look but lets have a look at some examples which clears your doubt.

Array#select! method in Ruby



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

# Extracting all the odd numbers
# It instead modifies the existing data.
numbers.select! { |number| number.odd? }
  => [2, 4, 6, 8, 10]

numbers
  => [2, 4, 6, 8, 10]

Array#reject! method in Ruby



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

# Rejecting all the even numbers
# It instead modifies the existing array.
numbers.reject! { |number| number.even? }
  => [1, 3, 5, 7, 9]

numbers
=> [1, 3, 5, 7, 9]

Now let’s have a look at extract! provided in Rails 6.


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

# Extracting all the even numbers
numbers.extract! { |number| number.even? }
  => [2, 4, 6, 8, 10]

numbers
  => [1, 3, 5, 7, 9]


Pull Request

Recommended Posts

Rails 5 adds OR Activerecord method
This or method was introduced in Rails 5, It returns a new ActiveRecord::Relation which is...
Descendants vs Subclasses in Ruby
Descendants has been a part of Rails ActiveSupport::DescendantsTracker for quite a while. However, Class#subsclasses is...
Ruby 3.1 adds subclasses method
Ruby 3.1 adds Class#subclasses method, which returns an array of subclasses directly inheriting from the...