2010-05-03 3 views
27

나는이 작품을 알고 :proc를 argument가있는 instance_eval과 함께 호출 하시겠습니까?

proc = Proc.new do 
    puts self.hi + ' world' 
end 

class Usa 
    def hi 
    "Hello!" 
    end 
end 
Usa.new.instance_eval &proc 

그러나 나는 시저에 인수를 전달하려는, 그래서이 작동하지 않는이 시도 :

proc = Proc.new do |greeting| 
    puts self.hi + greeting 
end 

class Usa 
    def hi 
    "Hello!" 
    end 
end 
Usa.new.instance_eval &proc, 'world' # does not work 
Usa.new.instance_eval &proc('world') # does not work 

이 사람이 나에게 그것이 작동되도록 도와 줄 수 있습니까?

+0

오타가 있습니다. 'gsub! ("gretting", "greeting")' –

+0

지금 고쳐졌습니다. 미안합니다. 고마워. 마크. –

답변

50

인수를 전달해야 할 때 instance_eval 대신 instance_exec을 사용하십시오.

proc = Proc.new do |greeting| 
    puts self.hi + greeting 
end 

class Usa 
    def hi 
    "Hello, " 
    end 
end 
Usa.new.instance_exec 'world!', &proC# => "Hello, world!" 

참고 : Ruby 1.8.7의 새로운 기능이므로 필요한 경우 업그레이드하거나 require 'backports'을 추가하십시오.

+2

'backports' *가 할 수없는 것이 있습니까? :-) –

+0

@ Jörg :-) 나는 거기에 있었으면 좋겠어. "Method # source_location"나 인코딩 물건처럼 너무 어둡다. 그리고'instance_exec'는 보석에서 가장 못생긴 해킹입니다 ... –

관련 문제