9
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 ?

ありがとう :)

4

3 に答える 3

13

最善の方法は次のとおりです。

def thank name
  yield name if block_given?
end
于 2010-08-04T15:36:07.173 に答える
9
def thank(arg, &block)
  yield arg
end

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

次に、次のことができます。

thank("God", &proc)
于 2010-08-04T15:40:13.813 に答える