Module: Enumerable

Defined in:
lib/inactive_support/enumerable/consecutive_by.rb

Instance Method Summary collapse

Instance Method Details

#consecutive?(&block) ⇒ Boolean

Returns:

  • (Boolean)


14
15
16
17
18
19
20
# File 'lib/inactive_support/enumerable/consecutive_by.rb', line 14

def consecutive?(&block)
  if block_given?
    consecutive_by(&block).count == 1 && self.sorted?(&block)
  else
    consecutive_by(&:identity).count == 1 && self.sorted?(&block)
  end
end

#consecutive_byObject



3
4
5
6
7
8
9
10
11
12
# File 'lib/inactive_support/enumerable/consecutive_by.rb', line 3

def consecutive_by
  sorted = sort { |a, b| _ordinal(yield(a)) <=> _ordinal(yield(b)) }

  prev = sorted.first

  sorted.slice_before do |cur|
    prev, prev2 = cur, prev
    _ordinal(yield(prev2)) + 1 != _ordinal(yield(prev))
  end.to_a
end

#sorted?Boolean

Returns:

  • (Boolean)


22
23
24
25
26
27
28
29
30
31
32
# File 'lib/inactive_support/enumerable/consecutive_by.rb', line 22

def sorted?
  if block_given?
    each_cons(2).all? do |a, b|
      (_ordinal(yield(a)) <=> _ordinal(yield(b))) <= 0
    end
  else
    each_cons(2).all? do |a, b|
      (_ordinal(a).to_i <=> _ordinal(b).to_i) <= 0
    end
  end
end