My solution to the problem: Iterator.
class Iterator
include Enumerable
class Iteration
def initialize(&block)
@block = block
end
def yield(*args)
@block.call(*args)
end
end
def initialize(&iterator)
@iterator = iterator
end
def each(&block)
@iterator.call(Iteration.new(&block))
end
end
With that you can enable a method to return an Iterator with a single statement, which in turn allows you to do things like: dir.entries.select { ... }, where dir.entries returns an Iterator.
Example use:
def each_custom
if block_given? then
@custom.each { |element| yield(element) }
else
Iterator.new { |iter| @custom.each { |element| iter.yield(element) } }
end
end
1 comment:
Post a Comment