module Enumerable
Public Instance Methods
Returns an array of all elements in enum for which pattern
approximately matches element
(see Amatch::Levenshtein#search). If the optional block
is supplied, each matching element is passed to it, and the enum itself is returned.
LIMITATIONS:
-
Only strings are allowed as
pattern
. Regular expressions are reverted to their respective source. (Equivalent toagrep -k
) -
Only works with string elements in enum. (Calls
to_s
on each element) -
The cost for individual error types (substitution, insertion, deletion) cannot be adjusted.
# File lib/nuggets/enumerable/agrep.rb 56 def agrep(pattern, distance = 0) 57 pattern = pattern.source if pattern.is_a?(::Regexp) 58 59 am = ::Amatch::Levenshtein.new(pattern) 60 ma = lambda { |i| am.search(i.to_s) <= distance } 61 62 block_given? ? each { |i| yield i if ma[i] } : select(&ma) 63 end
Maximum minmax
. If what
is omitted, or nil
, the original Enumerable#max
is called.
# File lib/nuggets/enumerable/minmax.rb 95 def max(what = nil, &block) 96 what ? minmax(:max, what) : _nuggets_original_max(&block) 97 end
Maximum minmax_by
.
# File lib/nuggets/enumerable/minmax.rb 54 def max_by(by = nil, &block) 55 by.nil? || by.is_a?(::Numeric) ? 56 _nuggets_original_max_by(by, &block) : minmax_by(:max, by) 57 end
Minimum minmax
. If what
is omitted, or nil
, the original Enumerable#min
is called.
# File lib/nuggets/enumerable/minmax.rb 104 def min(what = nil, &block) 105 what ? minmax(:min, what) : _nuggets_original_min(&block) 106 end
Minimum minmax_by
.
# File lib/nuggets/enumerable/minmax.rb 63 def min_by(by = nil, &block) 64 by.nil? || by.is_a?(::Numeric) ? 65 _nuggets_original_min_by(by, &block) : minmax_by(:min, by) 66 end
Finds the minmax_by
according to what
and returns that “what”.
Example:
%w[a bcd ef].max(:length) #=> 3
# File lib/nuggets/enumerable/minmax.rb 75 def minmax(meth = nil, what = nil, &block) 76 return _nuggets_original_minmax(&block) unless meth 77 78 #m = minmax_by(meth, what) 79 #what.is_a?(Proc) ? what[m] : m.send(what) 80 81 _what = what.is_a?(::Proc) ? what : lambda { |i| i.send(what) } 82 map { |i| _what[i] }.send(meth) 83 84 # Benchmark (:max, :length; enum.size = 20, N = 100_000): 85 # 86 # max_by(:length).length 7.920000 0.890000 8.810000 ( 8.991915) 87 # map(:length).max 4.800000 0.600000 5.400000 ( 5.418114) 88 end
Finds the maximum/minimum (or whatever meth
is) value in enum according to by
(which may be a symbol/string that is sent to each value, or a proc that receives each value as parameter).
# File lib/nuggets/enumerable/minmax.rb 43 def minmax_by(meth = nil, by = nil, &block) 44 return _nuggets_original_minmax_by(&block) unless meth 45 46 _by = by.is_a?(::Proc) ? by : lambda { |i| i.send(by) } 47 send(meth) { |a, b| _by[a] <=> _by[b] } 48 end