코드 블록 instance_exec
을 취하여 적절한 결과를 얻을 수 있습니다. 다른 객체에서 메서드를 가져와 내 범위에서 메서드 중 하나를 호출하고 싶습니다. 다른 객체에서 메서드를 가져 와서 proc으로 변환 한 다음 instance_exec
으로 예상 한 결과를 얻지 못합니다. 코드는 다음과 같습니다.instance_exec를 사용하여 메소드를 Proc로 변환
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
그래, 나는 eval을 사용하지 않는 편이 좋을 것이다. 대신 코드 블록을 사용할 수 있습니다. – BeepDog