0

I have this snippet:

class MyClass
    def self.callWithBlock (&block)
        print block.blockVar
    end
end

MyClass::callWithBlock do
    blockVar = 'Hello'
end

which gives me an error:

in `callWithBlock': undefined method `blockVar' for #<Proc:0x000000017ed168@./block-test.rb:9> (NoMethodError)
    from ./block-test.rb:9:in `<main>'

How to access this blockVar?

1 Answer 1

2

If you add binding at the end of the block, that would become the result of call-ing the block, and you can eval whatever local variables assigned in that block within the context of the binding.

class MyClass
  def self.callWithBlock (&block)
    print block.call.eval('blockVar')
  end
end

MyClass::callWithBlock do
  blockVar = 'Hello'
  binding
end
# => Hello
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.