Rails 6 adds Array#extract!

Amit Choudhary avatar

Amit Choudhary

June 24, 2019

This blog is part of our  Rails 6 series.

Rails 6 added extract! on Array class. extract! removes and returns the elements for which the given block returns true.

extract! is different from reject! in the way that reject! returns the array after removing the elements whereas extract! returns removed elements from the array.

Let's checkout how it works.

Rails 6.0.0.beta2

Let's pluck all the user emails and then extract emails which include gmail.com.


> > emails = User.pluck(:email)
> > SELECT "users"."email" FROM "users"

=> ["[email protected]", "[email protected]", "[email protected]", "[email protected]"]

> > emails.extract! { |email| email.include?('gmail.com') }

=> ["[email protected]", "[email protected]", "[email protected]"]

> > emails

=> ["[email protected]"]

> > emails = User.pluck(:email)
> > SELECT "users"."email" FROM "users"

=> ["[email protected]", "[email protected]", "[email protected]", "[email protected]"]

> > emails.reject! { |email| email.include?('gmail.com') }

=> ["[email protected]"]

> > emails

=> ["[email protected]"]

Here is the relevant pull request.

Follow @bigbinary on X. Check out our full blog archive.