Hello i have a question about scopes of block
I want to define a block at one time.
But when it get’s called it should have the scope (vars ed )
of the calling environement
Example :
class BlockTest
attr_accessor :myblock
def process(&block)
self.myblock = block
end
end
t = BlockTest.new
t.process {
“var = #{out_of_scope_var}”
}
out_of_scope_var = “daniel”
p t.myblock.call
Results in :
blocktest.rb:15: undefined local variable or method `out_of_scope_var’
for main:Object (NameError) from blocktest.rb:19
How can i call the proc so that the out_of_scope_var is known :
Hello i have a question about scopes of block
I want to define a block at one time.
But when it get’s called it should have the scope (vars ed )
of the calling environement
Perhaps you will be satisfied that the block receive values from the
parent
environment. This is the normal way to solve the problem.
#!/usr/bin/ruby -w
class BlockTest
attr_accessor :myblock
def process(&block)
self.myblock = block
end
end
Perhaps you will be satisfied that the block receive values from the parent
environment. This is the normal way to solve the problem.
That is how it is solved now, but the proc needs to be flexible.
I call much proc’s and i don’t now what to pass.
It are not just vars that i want to accessible but also methods ed
out_of_scope_var = “out of scope, me”
t = BlockTest.new
t.process {“var = #{out_of_scope_var}”}
p t.myblock
#=> “var = out of scope, me”
###########
Hope this helps,
Gustav P.
Hi paul, i know that’s works, but i need it slightly differtent
because you set out_of_scope_var before you create the block
I want it to be accessible when you set it after you create the block
With your method it is in the scope of the block
I want the block to have access to the scope when you call it
So this should work :
class BlockTest
def process(&block)
@block=block
end
def myblock
instance_eval{@block}.call
end
end
t = BlockTest.new
t.process {“var = #{out_of_scope_var}”}
out_of_scope_var = “out of scope, me”
p t.myblock
But that gives :
blocktest.rb:40: undefined local variable or method out_of_scope_var' for main:Object (NameError) from blocktest.rb:34:inmyblock’
from blocktest.rb:45