问题
I realize that you can change the binding of a block using instance_eval
class Foo
def bar &block
instance_eval &block
end
end
Foo.new.bar { self } # returns the instance
But some built in methods accept blocks and in that case it doesn't seem possible to change the binding of the block without messing with the internals of the built in method.
class Foo
def enum &block
Enumerator.new &block
end
end
Foo.new.enum { self }.each {} # returns main!!!
Is there a way around this?
回答1:
You can work around it this way:
class Foo
def enum &block
Enumerator.new do |*args|
instance_exec *args, &block
end
end
end
But I'm confident that you cannot change the binding of an existing Proc
short of instance_eval
/instance_exec
-ing it.
来源:https://stackoverflow.com/questions/11587050/change-block-binding-without-eval