2010-08-04 29 views
1
proc = Proc.new do |name| 
    puts "Thank you #{name}!" 
end 
def thank 
    yield 
end 

proc.call # output nothing, just fine 
proc.call('God') # => Thank you God! 

thank &proC# output nothing, too. Fine; 
thank &proc('God') # Error! 
thank &proc.call('God') # Error! 
thank proc.call('God') # Error! 
# So, what should I do if I have to pass the 'God' to the proc and use the 'thank' method at the same time ? 

謝謝:)如何通過方法調用參數時將參數傳遞給proc? (紅寶石)

回答

8

我認爲最好的方法是:

def thank name 
    yield name if block_given? 
end 
7
def thank(arg, &block) 
    yield arg 
end 

proc = Proc.new do|name| 
    puts "Thank you #{name}" 
end 

然後,你可以這樣做:

thank("God", &proc) 
+0

您應該在每行代碼前加上2個空格,以使其成爲答案中的代碼示例。它看起來更漂亮,併爲所有代碼行添加語法高亮顯示。 – David 2010-08-04 15:50:43

+2

不需要',&block' – 2010-08-04 16:55:51

+0

@ Marc-AndréLafortune:你指的是'thank'的定義,而不是它的調用,對吧? – 2010-08-04 23:31:28

1

另一種方式:

proc = Proc.new do |name| 
    puts "thank you #{name}" 
end 

def thank(proc_argument, name) 
    proc_argument.call(name) 
end 

thank(proc, "God") #=> "thank you God" 
thank(proc, "Jesus") #=> "thank you Jesus" 

它的工作原理,但我不喜歡它。不過,它將幫助讀者理解如何使用特效和塊。