aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib
diff options
context:
space:
mode:
authorMatthew Draper <matthew@trebex.net>2018-08-15 03:01:05 +0930
committerGitHub <noreply@github.com>2018-08-15 03:01:05 +0930
commit7fa2f539fa2a7a1ebb5086023091983ce0d810d9 (patch)
treeedb47a67fd44ab9a6fad7a38239094f2146fdad9 /activesupport/lib
parentffc4703f22888dce0394fe0ab524a9e6cdc3c7e5 (diff)
parentb71abb3bb8cd177d1d3fceec88f54b505d616887 (diff)
downloadrails-7fa2f539fa2a7a1ebb5086023091983ce0d810d9.tar.gz
rails-7fa2f539fa2a7a1ebb5086023091983ce0d810d9.tar.bz2
rails-7fa2f539fa2a7a1ebb5086023091983ce0d810d9.zip
Merge pull request #33137 from bogdanvlviv/add-array-extract-method
Add `Array#extract!`
Diffstat (limited to 'activesupport/lib')
-rw-r--r--activesupport/lib/active_support/core_ext/array.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/array/extract.rb21
2 files changed, 22 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/array.rb b/activesupport/lib/active_support/core_ext/array.rb
index 6d83b76882..a2569c798b 100644
--- a/activesupport/lib/active_support/core_ext/array.rb
+++ b/activesupport/lib/active_support/core_ext/array.rb
@@ -3,6 +3,7 @@
require "active_support/core_ext/array/wrap"
require "active_support/core_ext/array/access"
require "active_support/core_ext/array/conversions"
+require "active_support/core_ext/array/extract"
require "active_support/core_ext/array/extract_options"
require "active_support/core_ext/array/grouping"
require "active_support/core_ext/array/prepend_and_append"
diff --git a/activesupport/lib/active_support/core_ext/array/extract.rb b/activesupport/lib/active_support/core_ext/array/extract.rb
new file mode 100644
index 0000000000..cc5a8a3f88
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/array/extract.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+class Array
+ # Removes and returns the elements for which the block returns a true value.
+ # If no block is given, an Enumerator is returned instead.
+ #
+ # numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+ # odd_numbers = numbers.extract! { |number| number.odd? } # => [1, 3, 5, 7, 9]
+ # numbers # => [0, 2, 4, 6, 8]
+ def extract!
+ return to_enum(:extract!) { size } unless block_given?
+
+ extracted_elements = []
+
+ reject! do |element|
+ extracted_elements << element if yield(element)
+ end
+
+ extracted_elements
+ end
+end