Block binding in Ruby
I am confused by the definition of block binding in ruby. Here are two samples:
def redfine_a(&block)
a = 2
puts eval("a", block.binding)
block.call
end
a = "hello"
puts redfine_a {a}
This one could run with the expected result, while the second one:
def redefine_a(&block)
a= 2
puts eval("a", block.binding)
block.call
end
puts redefine_a{a= "hello"}
will complain:
undefined local variable or method `a' fo开发者_运维技巧r main:Object (NameError)
After I removed the puts eval("a", block.binding)
, my code run:
def redefine_a(&block)
a= 2
block.call
end
puts redefine_a{a= "hello"}
Where am I wrong?
block.binding
is the environment in which the block is defined, before it runs.
In your code the context where the block is defined is the main
object, so the line eval("a", block.binding)
will return the value of a
in main
. In your first example a
is defined in main
and so the code runs, in the second example there is no a
in main and so the error.
In both cases though, the a=2
in your redefine_a
method can have no effect.
精彩评论