views:

42

answers:

2

Hi, I've been 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' for 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"}

Could anyone help me to understand where I am wrong?

+4  A: 

block.binding is the environment in which the block is defined, before it runs.

mckeed
+1  A: 

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.

banister