如何通过方法调用参数传递给proc?

问题描述 投票:7回答:3
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 ?

谢谢 :)

ruby parameters call block proc-object
3个回答
13
投票

我认为最好的方法是:

def thank name
  yield name if block_given?
end

8
投票
def thank(arg, &block)
  yield arg
end

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

然后你可以这样做:

thank("God", &proc)

2
投票

与Nada提出的不同的方式(它是相同的,只是不同的语法):

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

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

thank(proc, "for the music") #=> "thank you for the music"
thank(proc, "for the songs you're singing") #=> "thank you for the songs you're singing"

它有效,但我不喜欢它。然而,它将帮助读者了解如何使用过程和块。

© www.soinside.com 2019 - 2024. All rights reserved.