Module: Enumerable

Defined in:
lib/whisper/common.rb

Instance Method Summary collapse

Instance Method Details

#argfindObject



32
33
34
# File 'lib/whisper/common.rb', line 32

def argfind
  each { |e| x = yield(e) and return x; }; nil
end

#group_byObject



22
23
24
# File 'lib/whisper/common.rb', line 22

def group_by
  inject({}) { |h, e| x = yield e; h[x] = (h[x] || []) << e; h }
end

#group_by_multipleObject



26
27
28
# File 'lib/whisper/common.rb', line 26

def group_by_multiple
  inject({}) { |h, e| yield(e).each { |x| h[x] = (h[x] || []) << e }; h }
end

#map_byObject



18
19
20
# File 'lib/whisper/common.rb', line 18

def map_by
  inject({}) { |h, e| h[yield(e)] = e; h }
end

#max_of(&b) ⇒ Object



30
# File 'lib/whisper/common.rb', line 30

def max_of &b; map(&b).max end

#sumObject



36
# File 'lib/whisper/common.rb', line 36

def sum; inject(0) { |a, b| a + b } end

#thread(id_method, parent_id_method) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/whisper/common.rb', line 38

def thread id_method, parent_id_method
  branches = { :root => [:root, []] }

  each do |e|
    id = e.send(id_method) or next
    parent_id = e.send(parent_id_method) || :root
    if branches[id]
      thing, children = branches[id]
      raise ArgumentError, "multiple objects with #{id_method} #{id.inspect}" if thing
      branches[id] = [e, children]
    else
      branches[id] = [e, []]
    end
    branches[parent_id] ||= [nil, []]
    branches[parent_id][1] << e
  end

  tree = {}
  branches.each { |label, (thing, children)| tree[thing] = children }
  tree
end