Enumerator_Generator_select.rb

sample - Eike Dierks, 06/07/2012 06:47 AM

Download (806 Bytes)

 
1
#
2
#   sample for "Enumerator::Generator:select should return another Enumerator::Generator"
3
#   return the first five even integers starting at 123
4
#
5
#
6
class Range
7
    # wrap a range in a Enumerator::Generator
8
    def generator
9
        Enumerator.new{|y| self.each{|n|y<<n}}
10
    end
11
end
12

    
13

    
14

    
15
class Integer
16
    # return a generator for all integers starting at n
17
    def self.from n
18
        (n..Float::INFINITY).generator
19
    end
20
end
21

    
22

    
23
class Enumerator
24
    # return a generator for all elements from enumeration where block returns true
25
    def select &block
26
        Enumerator.new do |y|
27
            self.each do |obj|
28
                if block.call(obj)
29
                    y<<obj
30
                end
31
            end
32
        end
33
    end
34
end
35

    
36

    
37
# let's try it
38
p Integer.from(123).select{|n|n.even?}.take(5)
39

    
40

    
41