This blog is part of our Rails 6 series. 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.

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" => [ "amit.choudhary@bigbinary.com" , "amit@gmail.com" , "mark@gmail.com" , "sam@gmail.com" ] >> emails . extract! { | email | email . include? ( 'gmail.com' ) } => [ "amit@gmail.com" , "mark@gmail.com" , "sam@gmail.com" ] >> emails => [ "amit.choudhary@bigbinary.com" ] >> emails = User . pluck ( :email ) SELECT "users" . "email" FROM "users" => [ "amit.choudhary@bigbinary.com" , "amit@gmail.com" , "mark@gmail.com" , "sam@gmail.com" ] >> emails . reject! { | email | email . include? ( 'gmail.com' ) } => [ "amit.choudhary@bigbinary.com" ] >> emails => [ "amit.choudhary@bigbinary.com" ]

Here is the relevant pull request.