0

Is there any way to access object from block which was defined inside different scope? Sorry if it's confusing, I provide a little example:

def scope(&block)
  foo = "bar"
  instance_eval &block
end

scope do
  puts "foo is #{foo}"
end

I'd like to get the output:

"foo is bar"

Is it possible?

4
  • You could explicitly pass parameters to the block. Aug 28, 2012 at 16:56
  • Yes, I know, sorry that I didn't say it earlier. :( I'm looking for some way to do it without passing parameter to the block.
    – evfwcqcg
    Aug 28, 2012 at 16:58
  • What exactly are you trying to accomplish? Aug 28, 2012 at 17:00
  • Look at my answer. Are you sure it's not what you want? :) Aug 28, 2012 at 17:01

1 Answer 1

2

The real question is what you're trying to do, but the closest you can get is this:

def scope
  @foo = "bar"
  yield
end

scope do
  puts "foo is #{@foo}"
end

Note the use of an instance variable @foo instead of a local variable. You can't access the instance variable unless you do so explicitly, like this:

def scope
  foo = "bar"
  yield foo
end

scope do |foo|
  puts "foo is #{foo}"
end

But this is good. Otherwise it would be difficult to avoid conflicts with your local variables.

Note: I've also replaced your use of an explicit &block with the implicit yield. The yield form requires a block to be present, and has a simpler syntax, but it is largely a matter of style.

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.