Project

General

Profile

Feature #15831

Updated by bogdanvlviv (Bogdan Denkovych) almost 5 years ago

## Add `Array#extract` 

 The method removes and returns the elements for which the block returns a true value. 
 If no block is given, an Enumerator is returned instead. 

 ```ruby 
 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] 
 ``` 

 This method was added to Active Support as `extract!` in https://github.com/rails/rails/pull/33137 

 In this post, you can find use cases of this method 
 https://bogdanvlviv.com/posts/ruby/rails/array-extract-to-activesupport-6-0.html 


 ## Add `Hash#extract` 

 The method removes and returns the key/value pairs for which matching the block evaluates to +true+. 
 If no block is given, an Enumerator is returned instead. given keys. 

 ```ruby 
 h = {a: 100, b: 200, c: 300} 
 h.extract {|k, v| v > 150} h.extract(:a) # => {:a=>100} 
 h # => {:b=>200, :c=>300} 
 h.extract(:b, :c, :d) # => {:b=>200, :c=>300} 
 h # => {:a=>100} {} 
 ``` 

 Note that there is This method `extract!` in was added to Active Support that was added as `extract!` in 2009, see 
 https://github.com/rails/rails/commit/8dcf91ca113579646e95b0fd7a864dfb6512a53b 
 But I think we should upstream `extract!` to Ruby as `slice!`. 


 

 ## Add `ENV::extract` 

 The method removes and returns the key/value pairs for which matching the block evaluates to +true+. 
 If no block is given, an Enumerator is returned instead. given keys. 

 ```ruby 
 ENV.extract {|k, v| k == "PORT"} ENV.extract("PORT", "RAILS_ENV") # => {"PORT"=>"3000"} {"PORT"=>"3000", "RAILS_ENV"=>"development"} 
 ``` 


 

 Pull Request: https://github.com/ruby/ruby/pull/2171

Back