Created
July 1, 2016 14:38
-
-
Save IronSavior/195d4434258b2137aca1015e7bcc8588 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BaseEnum | |
include Enumerable | |
attr_reader :ctx | |
def initialize( *ctx ) | |
@ctx = ctx | |
end | |
def each( *args, &blk ) | |
return enum_for __callee__, *args unless block_given? | |
projection *args do |obj, *ctx| | |
yield_with_context obj, *ctx, &blk | |
end | |
end | |
private | |
def yield_with_context( obj, *ctx, &blk ) | |
fail 'Block required' unless block_given? | |
args = (-1...1).include?(blk.arity) ? obj : [obj, *ctx] | |
yield *args | |
end | |
end | |
class Enum < BaseEnum | |
def projection( *args ) | |
i = 0 | |
ctx.each do |obj| | |
yield obj, i | |
i += 1 | |
end | |
end | |
end | |
e0 = Enum.new *%w[zero one two three] | |
Array e0 | |
e0.each do |obj, i| | |
puts ' ** %03d: %s (%s)' % [i, obj, obj.class] | |
end | |
e0.each do |obj, *args| | |
puts args | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment