Module: Enumerable

Defined in:
lib/invoca/utils/enumerable.rb,
lib/invoca/utils/map_compact.rb,
lib/invoca/utils/stable_sort.rb

Overview

Invoca ::Enumerable extensions

Instance Method Summary collapse

Instance Method Details

#*Object



38
39
40
# File 'lib/invoca/utils/enumerable.rb', line 38

def *
  Invoca::Utils::MultiSender.new(self, :map)
end

#build_hash(res = {}) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/invoca/utils/enumerable.rb', line 22

def build_hash(res = {})
  each do |x|
    pair = block_given? ? yield(x) : x
    res[pair.first] = pair.last if pair
  end
  res
end

#map_and_find(not_found = nil) ⇒ Object



7
8
9
10
11
12
13
# File 'lib/invoca/utils/enumerable.rb', line 7

def map_and_find(not_found = nil)
  each do |x|
    val = yield(x)
    return val if val
  end
  not_found
end

#map_compactObject



4
5
6
7
8
9
10
11
# File 'lib/invoca/utils/map_compact.rb', line 4

def map_compact
  result = []
  each do |item|
    selected = yield(item)
    result << selected unless selected.nil?
  end
  result
end

#map_hash(res = {}) ⇒ Object



30
31
32
33
34
35
36
# File 'lib/invoca/utils/enumerable.rb', line 30

def map_hash(res = {})
  each do |x|
    v = yield x
    res[x] = v
  end
  res
end

#map_with_index(res = []) ⇒ Object



15
16
17
18
19
20
# File 'lib/invoca/utils/enumerable.rb', line 15

def map_with_index(res = [])
  each_with_index do |x, i|
    res << yield(x, i)
  end
  res
end

#stable_sortObject

A stable sort will preserve the original order of two elements if their sort keys are identical.



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/invoca/utils/stable_sort.rb', line 7

def stable_sort
  n = -1
  if block_given?
    collect {|x| n += 1; [x, n]
    }.sort! {|a, b|
      c = yield a[0], b[0]
      if c.nonzero? then c else a[1] <=> b[1] end
    }.collect! {|x| x[0]}
  else
    sort_by {|x| n += 1; [x, n]}
  end
end

#stable_sort_byObject



20
21
22
23
24
# File 'lib/invoca/utils/stable_sort.rb', line 20

def stable_sort_by
  block_given? or return enum_for(:stable_sort_by)
  n = -1
  sort_by {|x| n += 1; [(yield x), n]}
end