Class: Array
- Defined in:
- lib/shenanigans/array/caret.rb,
lib/shenanigans/array/zip_with.rb,
lib/shenanigans/array/reductions.rb,
lib/shenanigans/array/random_subarray.rb
Instance Method Summary collapse
-
#^(other) ⇒ Object
Returns an array containing elements exclusive between two arrays.
-
#random_subarray(n = 1) ⇒ Object
Generates random subarrays.
-
#reductions(*args, &block) ⇒ Object
Similar to
reduce
/inject
, but also returns intermediate values. -
#zip_with(other, op = nil) ⇒ Object
Zip
self
withother
, combining the elements with the provided block or symbol.
Instance Method Details
#^(other) ⇒ Object
Returns an array containing elements exclusive between two arrays.
6 7 8 |
# File 'lib/shenanigans/array/caret.rb', line 6 def ^(other) (self - other) | (other - self) end |
#random_subarray(n = 1) ⇒ Object
Generates random subarrays. Uses random numbers and bit-fiddling to assure performant uniform distributions even for large arrays.
10 11 12 13 14 15 16 17 |
# File 'lib/shenanigans/array/random_subarray.rb', line 10 def (n = 1) raise ArgumentError, "negative argument" if n < 0 (1..n).map do r = rand(2**size) select.with_index { |_, i| r[i] == 1 } end end |
#reductions(*args, &block) ⇒ Object
Similar to reduce
/inject
, but also returns intermediate values. Has the same interface as reduce
/inject
, so an initial value, an operator or both can be supplied. This method may eventually be moved to the Enumerable
module.
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/shenanigans/array/reductions.rb', line 14 def reductions(*args, &block) arr = dup if args.size == 1 Symbol === (arg = args.first) ? op = arg : initial = arg else initial, op, _ = args end raise ArgumentError, "Need an operator or block" unless op || block initial ||= arr.shift arr.inject([initial, [initial]]) { |(acc, result), el| val = op ? acc.send(op, el) : yield(acc, el) [val, result << val] }.last end |
#zip_with(other, op = nil) ⇒ Object
Zip self
with other
, combining the elements with the provided block or symbol. The resulting array will be as long as the shorter of the two arrays.
12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/shenanigans/array/zip_with.rb', line 12 def zip_with(other, op = nil) return [] if empty? || other.empty? clipped = self[0..other.length - 1] zipped = clipped.zip(other) if op zipped.map { |a, b| a.send(op, b) } else zipped.map { |a, b| yield(a, b) } end end |