How to call a ruby block to get access to the caller bindings
Inside the block you are not in the scope of the Blocks
instance, so foo
is not visible. You have to pass the object to the block if you want to have access to it:
class Blocks # ... def run @block.call(self) end # ...endblk = Blocks.new { |b| b.foo }blk.run# => "foo"
Alternatively you can pass the block to instance_eval
:
class Blocks # ... def run instance_eval(&@block) end # ...endblk = Blocks.new { foo }blk.run# => "foo"
Tried to reproduce it :
3.times.map{ foo }#~> undefined local variable or method `foo' for main:Object (NameError)
Inside { }
or outside of {}
, foo
has not been defined as a method
or varable
. Thus Ruby parser got confused and throws error.
Now see:
foo = 123.times.map{ foo }# => [12, 12, 12]
Try :
test "say method_foo" do assert_equal( 'foo', Blocks.new{|i| i.foo }.run )end