我可以获取一段代码,instance_exec
然后得到正确的结果。我想从另一个对象中取出一个方法,并在我的范围内调用其中一个方法。当我从不同的对象中获取一个方法时,将它变成一个过程,然后instance_exec
它,我没有得到预期的结果。代码如下。
class Test1
def ohai(arg)
"magic is #{@magic} and arg is #{arg}"
end
end
class Test2
def initialize
@magic = "MAGICAL!"
end
def scope_checking
@magic
end
def do_it
ohai = Test1.new.method(:ohai)
self.instance_exec("foobar", &ohai)
end
end
describe "Test2 and scopes" do
before do
@t2 = Test2.new
end
it "has MAGICAL! in @magic" do
@t2.scope_checking.should == "MAGICAL!"
end
# This one fails :(
it "works like I expect converting a method to a proc" do
val = @t2.do_it
val.should == "magic is MAGICAL! and arg is foobar"
end
it "should work like I expect" do
val = @t2.instance_exec do
"#{@magic}"
end
val.should == "MAGICAL!"
end
end