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?
The real question is what you’re trying to do, but the closest you can get is this:
Note the use of an instance variable
@fooinstead of a local variable. You can’t access the instance variable unless you do so explicitly, like this: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
&blockwith the implicityield. Theyieldform requires a block to be present, and has a simpler syntax, but it is largely a matter of style.