Module: Enumerable
- Defined in:
- lib/rails_extensions/enumerable.rb
Instance Method Summary collapse
-
#mean(init = 0.0, &block) ⇒ Object
Calculates a mean of the elements in the enumerable.
-
#with_gap_index(offset = 0, with_identifier: false, &block) ⇒ Object
Calculates the position of values allowing gaps.
Instance Method Details
#mean(init = 0.0, &block) ⇒ Object
Calculates a mean of the elements in the enumerable. [1, 2, 3, 4, 5].mean # => 3.0
6 7 8 9 10 11 12 13 14 |
# File 'lib/rails_extensions/enumerable.rb', line 6 def mean(init = 0.0, &block) return init if empty? if block_given? map(&block).mean(init) else sum(init) / size.to_f end end |
#with_gap_index(offset = 0, with_identifier: false, &block) ⇒ Object
Calculates the position of values allowing gaps. The return value is an array of arrays, each containing the original value and its position. If each values has an identifier, set the identifier as the first element of value and use with_identifier parameter.
{a:2, b:3, c:5, d:2}.with_gap_index(with_identifier: true) # =>
[[:a, 2, 0], [:d, 2, 0], [:b, 3, 2], [:c, 5, 3]]
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/rails_extensions/enumerable.rb', line 22 def with_gap_index(offset = 0, with_identifier: false, &block) if block_given? map(&block).with_gap_index(offset, with_identifier: with_identifier) else new_array = [] current_pos = offset each_with_index do |ele, idx| same_as_previous = with_identifier ? ele.second == self[idx - 1].second : ele == self[idx - 1] current_pos = idx + offset unless same_as_previous new_array.push([ele, current_pos].flatten) end new_array end end |