Module: WrapIt::CaptureArray
- Defined in:
- lib/wrap_it/capture_array.rb
Overview
Adds #capture! and #capture_first! methods to array. Theese methods are extracts items from array by some conditions and returns its as separate array for #capture! and as first item for #capture_first!.
Constant Summary collapse
- REQUIRED_METHODS =
%i(reject! find_index delete_at)
Instance Method Summary collapse
-
#capture!(*args, &block) ⇒ Array
Extracts elements from array by conditions, passed in arguments and returns theese elements as new array.
-
#capture_first!(*args, &block) ⇒ Object
Extracts first element from array that is satisfy conditions, passed in arguments and returns these element.
Instance Method Details
#capture!([condition, ...], opts = {}) ⇒ Array #capture! {|element| ... } ⇒ Array
Extracts elements from array by conditions, passed in arguments and returns theese elements as new array.
Condition can be Regexp, Class, Array, lambdas and any other value. if condition contains labdas, all off them will be called before tests and results of theese calls will be used as conditions.
If condition is Regexp, all elements of array are tested for matching
to this regexp, previously converted to String by their to_s method. If
condition is an Array, all elements tested if it included in these
array. If the condition is a class, then elements are tested via is_a?
method for this class. true and false conditions do exactly what it
mean - true will satisfy condition, false will not. For any other
value, elements are tested with equality operator ==.
You can provide a block. In this case, all arguments are ignored, and
block yielded for each element of array. If block returns true,
element extracted from array.
All conditions, passed as arguments are or-ed so String, Symbol means
select Symbol or String elements.
You can also specify and option, so all tests will be and'ed with its
conditions.
97 98 99 100 101 102 103 |
# File 'lib/wrap_it/capture_array.rb', line 97 def capture!(*args, &block) captureed = [] reject! do |arg| do_compare(arg, *args, &block) && (captureed << arg) && true end captureed end |
#capture_first!(*args, &block) ⇒ Object
Extracts first element from array that is satisfy conditions, passed in arguments and returns these element.
110 111 112 113 |
# File 'lib/wrap_it/capture_array.rb', line 110 def capture_first!(*args, &block) index = find_index { |arg| do_compare(arg, *args, &block) } index.nil? ? nil : delete_at(index) end |