Module: WrapIt::ArgumentsArray
- Defined in:
- lib/wrap_it/arguments_array.rb
Overview
Adds #extract! and #extarct_first! methods to array. Theese methods are extracts items from array by some condirions and returns its as separate array for #extract! and as first item for #extract_first!.
Constant Summary collapse
- REQUIRED_METHODS =
%i(reject! find_index delete_at)
Class Method Summary collapse
Instance Method Summary collapse
-
#extract!(*args) {|element| ... } ⇒ Array
Extracts elements from array by conditions, passed in arguments nad returns theese elements as new array.
-
#extract_first!(*args, &block) ⇒ Object
Extracts first element from array that is satisfy conditions, passed in arguments and returns these element.
Class Method Details
.included(base) ⇒ Object
12 13 14 15 16 17 18 19 20 |
# File 'lib/wrap_it/arguments_array.rb', line 12 def self.included(base) methods = base.methods # avoid including in classes thats doen't have methods, used in # inplementation REQUIRED_METHODS.all? { |m| methods.include?(m) } || fail( TypeError, "#{self.class.name} can't be included into #{base.class.name}" ) end |
Instance Method Details
#extract!([condition, ..., options]) ⇒ Array #extract!(&block) ⇒ Array
Extracts elements from array by conditions, passed in arguments nad returns theese elements as new array.
Condition can be Regexp, class, Array and any other value. 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. 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.
88 89 90 91 92 93 94 |
# File 'lib/wrap_it/arguments_array.rb', line 88 def extract!(*args, &block) extracted = [] reject! do |arg| do_compare(arg, *args, &block) && extracted << arg && true end extracted end |
#extract_first!(*args, &block) ⇒ Object
Extracts first element from array that is satisfy conditions, passed in arguments and returns these element.
101 102 103 104 |
# File 'lib/wrap_it/arguments_array.rb', line 101 def extract_first!(*args, &block) index = find_index { |arg| do_compare(arg, *args, &block) } index.nil? ? nil : delete_at(index) end |