Project

General

Profile

Feature #6552 ยป Enumerator_Generator_select.rb

sample - eike.rb (Eike Dierks), 06/07/2012 06:47 AM

 
#
# sample for "Enumerator::Generator:select should return another Enumerator::Generator"
# return the first five even integers starting at 123
#
#
class Range
# wrap a range in a Enumerator::Generator
def generator
Enumerator.new{|y| self.each{|n|y<<n}}
end
end



class Integer
# return a generator for all integers starting at n
def self.from n
(n..Float::INFINITY).generator
end
end


class Enumerator
# return a generator for all elements from enumeration where block returns true
def select &block
Enumerator.new do |y|
self.each do |obj|
if block.call(obj)
y<<obj
end
end
end
end
end


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



    (1-1/1)