Class: Iter

Inherits:
Object show all
Defined in:
lib/epitools/iter.rb

Overview

A stable iterator class. (You can reorder/remove elements in the container without affecting iteration.)

For example, to reverse all the elements in a list:

>> i = Iter.new(1..10)
>> i.each_cons(2) { |a,b| b.move_before(a) }
>> i.to_a    #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Defined Under Namespace

Classes: Elem

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(vals) ⇒ Iter


15
16
17
# File 'lib/epitools/iter.rb', line 15

def initialize(vals)
  @container = vals.map { |val| elem(val) }
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object


58
59
60
61
62
63
64
65
66
# File 'lib/epitools/iter.rb', line 58

def method_missing(name, *args)
  result = @container.send(name, *args)
  case result
  when Array
    Iter.from_elems result
  else
    result
  end
end

Instance Attribute Details

#containerObject

Returns the value of attribute container


13
14
15
# File 'lib/epitools/iter.rb', line 13

def container
  @container
end

Class Method Details

.from_elems(elems) ⇒ Object


24
25
26
# File 'lib/epitools/iter.rb', line 24

def self.from_elems(elems)
  new([]).tap { |i| i.container = elems }
end

Instance Method Details

#==(other) ⇒ Object


28
29
30
31
32
33
34
35
# File 'lib/epitools/iter.rb', line 28

def ==(other)
  case other
  when Iter
    @container == other.container
  when Array
    @container == other
  end
end

#eachObject


37
38
39
40
41
42
# File 'lib/epitools/iter.rb', line 37

def each
  @container.each do |elem|
    yield elem
    elem.visited = true
  end
end

#each_cons(num = 1) ⇒ Object Also known as: iterate, every


44
45
46
47
48
49
# File 'lib/epitools/iter.rb', line 44

def each_cons(num=1)
  @container.each_cons(num) do |(*elems)|
    yield *elems
    elems.each { |e| e.visited = true }
  end
end

#elem(val) ⇒ Object

Wrap a value in an Elem container


20
21
22
# File 'lib/epitools/iter.rb', line 20

def elem(val)
  Elem.new(self, val)
end

#to_aObject


54
55
56
# File 'lib/epitools/iter.rb', line 54

def to_a
  @container.map(&:val)
end