Module: Enumerable
- Defined in:
- lib/whisper/common.rb
Instance Method Summary collapse
- #argfind ⇒ Object
- #group_by ⇒ Object
- #group_by_multiple ⇒ Object
- #map_by ⇒ Object
- #max_of(&b) ⇒ Object
- #sum ⇒ Object
- #thread(id_method, parent_id_method) ⇒ Object
Instance Method Details
#argfind ⇒ Object
32 33 34 |
# File 'lib/whisper/common.rb', line 32 def argfind each { |e| x = yield(e) and return x; }; nil end |
#group_by ⇒ Object
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_multiple ⇒ Object
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_by ⇒ Object
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 |
#sum ⇒ Object
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 |