We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.
Rails 6.0 was recently released.
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.
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=> ["amit.choudhary@bigbinary.com", "amit@gmail.com", "mark@gmail.com", "sam@gmail.com"]
6
7> > emails.extract! { |email| email.include?('gmail.com') }
8
9=> ["amit@gmail.com", "mark@gmail.com", "sam@gmail.com"]
10
11> > emails
12
13=> ["amit.choudhary@bigbinary.com"]
14
15> > emails = User.pluck(:email)
16> > SELECT "users"."email" FROM "users"
17
18=> ["amit.choudhary@bigbinary.com", "amit@gmail.com", "mark@gmail.com", "sam@gmail.com"]
19
20> > emails.reject! { |email| email.include?('gmail.com') }
21
22=> ["amit.choudhary@bigbinary.com"]
23
24> > emails
25
26=> ["amit.choudhary@bigbinary.com"]
Here is the relevant pull request.