Rails 6 Method: #Array.extract!

- 1 min

Calling the new Rails 6 method extract! (Pull request here) on an array will remove and return the elements for which the given block returns true.

Because I recently remembered what a great book Ender’s Game (and, due to my low expectations, surprisingly alright movie) is, take the following code block that extracts characters in the Wiggin family, modifying the original characters array.

>> characters = ['Petra Arkanian', 'Ender Wiggin', 'Bean', 'Mazer Rackham', 'Valentine Wiggin', 'Peter Wiggin']

=> ["Petra Arkanian", "Ender Wiggin", "Bean", "Mazer Rackham", "Valentine Wiggin", "Peter Wiggin"]

>> characters.extract! { |character| character.include?('Wiggin') }

=> ["Ender Wiggin", "Valentine Wiggin", "Peter Wiggin"]

This new method is basically the opposite of reject! since reject! returns the array after the elements have been removed, and extract! will return the elements that were removed from the array. Here’s the example using reject!.

>> characters = ['Petra Arkanian', 'Ender Wiggin', 'Bean', 'Mazer Rackham', 'Valentine Wiggin', 'Peter Wiggin']

=> ["Petra Arkanian", "Ender Wiggin", "Bean", "Mazer Rackham", "Valentine Wiggin", "Peter Wiggin"]

>> characters.reject! { |character| character.include?('Wiggin') }

=> ["Petra Arkanian", "Bean", "Mazer Rackham"]

Fun fact: There’s also a #Hash.extract! method.

Samantha Louise Causey

Samantha Louise Causey

Junior Rails dev @ Annkissam. BA in Computer Science from Smith College, 2017.

comments powered by Disqus
rss facebook twitter github youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora