2010-05-03 92 views
27

我知道這個工程:用參數調用帶有instance_eval的proc?

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

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

但是我想參數傳遞給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」,「問候」)' – 2010-05-03 15:45:31

+0

現在已經修復。對於那個很抱歉。謝謝馬克。 – 2010-05-03 15:51:10

回答

50

使用instance_exec代替instance_eval當你需要傳遞參數。

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' *不能做*嗎? :-) – 2010-05-03 16:00:59

+0

@Jörg:-)我希望沒有......太糟糕了,有些東西遙不可及,比如'Method#source_location'或編碼的東西。而'instance_exec'是寶石中最醜陋的黑客...... – 2010-05-03 16:11:25