如何通过方法调用参数传递给proc?(红宝石)

Cro*_*lio 8 ruby parameters block call proc-object

proc = Proc.new do |name|
  puts "Thank you #{name}!"
end
def thank
  yield
end
Run Code Online (Sandbox Code Playgroud)
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 ?
Run Code Online (Sandbox Code Playgroud)

谢谢 :)

Dan*_*ara 13

我认为最好的方法是:

def thank name
  yield name if block_given?
end
Run Code Online (Sandbox Code Playgroud)


Nad*_*leh 8

def thank(arg, &block)
  yield arg
end

proc = Proc.new do|name|
   puts "Thank you #{name}"
end
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

thank("God", &proc)
Run Code Online (Sandbox Code Playgroud)

  • 不需要`,&block` (2认同)