Skip to content

Instantly share code, notes, and snippets.

@IronSavior
Created July 1, 2016 14:38
Show Gist options
  • Save IronSavior/195d4434258b2137aca1015e7bcc8588 to your computer and use it in GitHub Desktop.
Save IronSavior/195d4434258b2137aca1015e7bcc8588 to your computer and use it in GitHub Desktop.
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