Rails 6 adds Array#extract!

Amit Choudhary

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.

1
2> > emails = User.pluck(:email)
3> > SELECT "users"."email" FROM "users"
4
5=> ["[email protected]", "[email protected]", "[email protected]", "[email protected]"]
6
7> > emails.extract! { |email| email.include?('gmail.com') }
8
9=> ["[email protected]", "[email protected]", "[email protected]"]
10
11> > emails
12
13=> ["[email protected]"]
14
15> > emails = User.pluck(:email)
16> > SELECT "users"."email" FROM "users"
17
18=> ["[email protected]", "[email protected]", "[email protected]", "[email protected]"]
19
20> > emails.reject! { |email| email.include?('gmail.com') }
21
22=> ["[email protected]"]
23
24> > emails
25
26=> ["[email protected]"]

Here is the relevant pull request.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.