12

I want to have access to the bindings of the caller. What's wrong here?

require 'test/unit'

class BlocksTest < Test::Unit::TestCase

  class Blocks
    def initialize( &block ); @block = block; end
    def run; instance_eval { @block.call }; end

    def foo; 'foo'; end
  end

  def test_say_foo_via_string
    assert_equal( 'foo', Blocks.new{ 'foo' }.run )
  end
  # => successful

  def test_say_foo_via_caller_method
    assert_equal( 'foo', Blocks.new{ foo }.run )
  end
  # => NameError: undefined local variable or method `foo'

end

Why i don't have access to the caller instance within the given block?

1
  • Dear Downvoter! I'm relatively new here and it would be nice getting some advices if my question is not useful. :-) I changed the question code to a complete test class BlocksTest. I also changed the block call in the run method from @block.call to instance_eval { @block.call } which raises the same error.
    – sschmeck
    Jul 2, 2013 at 9:19

3 Answers 3

6

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
  # ...
end

blk = 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
  # ...
end

blk = Blocks.new { foo }
blk.run
# => "foo"
3
  • For the difference between a proc and a block see this and this.
    – toro2k
    Jul 1, 2013 at 12:12
  • Thanks! I tried the second solution before i asked the question but without the & operator. instance_eval { @block.call }; raises the same error. What's the difference between the block and the Proc syntax?
    – sschmeck
    Jul 1, 2013 at 12:17
  • Thanks for the links. I didn't found an explanation for the difference between instance_eval( &block ) and instance_eval { block.call }. The first way converts the Proc to a block and the second creates a new block and executes the Proc. I have still no idea why the bindings/scopes of the approaches differ. :-/
    – sschmeck
    Jul 2, 2013 at 5:31
0

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 = 12
3.times.map{ foo }
# => [12, 12, 12]

Try :

test "say method_foo" do
  assert_equal( 'foo', Blocks.new{|i| i.foo }.run )
end
0

try this

class Blocks
  def initialize( &block ); @block = block; end
  def run; instance_eval &@block; end

  def foo; 'foo'; end
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.