Module: Enumerable

Overview

extracted from ActiveRecord (rubyforge.org/projects/activesupport/)

Instance Method Summary collapse

Instance Method Details

#each_consecutive_pairObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/strokedb/core_ext/enumerable.rb', line 22

def each_consecutive_pair
  first = true
  prev = nil

  each do |val|
    unless first
      yield prev, val
    else
      first = false
    end

    prev = val
  end
end

#group_byObject

Collect an enumerable into sets, grouped by the result of a block. Useful, for example, for grouping records by date.



6
7
8
9
10
11
# File 'lib/strokedb/core_ext/enumerable.rb', line 6

def group_by
  inject({}) do |groups, element|
    (groups[yield(element)] ||= []) << element
    groups
  end
end

#map_with_indexObject Also known as: collect_with_index

Map and each_with_index combined.



14
15
16
17
18
# File 'lib/strokedb/core_ext/enumerable.rb', line 14

def map_with_index
  collected=[]
  each_with_index {|item, index| collected << yield(item, index) }
  collected
end