Hi,
In message "[ruby-talk:4883] Re-binding a block"
on 00/09/12, Dave Thomas <Dave / thomases.com> writes:
| class Dave
| @@block = proc { puts @name }
| @name = "class level"
| def initialize
| @name = "instance level"
| end
|
| def block
| @@block.call
| end
| end
|
| Dave.new.block
|
|It will always output "class level" as @name is bound at the time the
|block is created. Is there any way to change that binding at runtime
|so that I can call the block and have it output "instance level"?
Here's the trick. Don't tell anybody. ;-)
class Matz
@@block = proc { puts @name }
@name = "class level"
def initialize
@name = "instance level"
end
def block
self.instance_eval(&@@block)
end
end
Matz.new.block
matz.