当通过方法调用程序时,如何传递参数给proc?

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 ?

感谢您的选择 :)
3个回答

13

我认为最好的方法是:

def thank name
  yield name if block_given?
end

9
def thank(arg, &block)
  yield arg
end

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

那么你可以这样做:

thank("God", &proc)

在你的回答中,每行代码前应添加2个空格,以使其成为代码示例。这样看起来更漂亮,并且可以为所有代码行添加语法高亮。 - David
@Marc-André Lafortune:你指的是定义 thank,而不是调用它,对吗? - Andrew Grimm
@Andrew:没错,这就是为什么我写了“,&block不需要”,而不是“,&proc需要”的原因。 - Marc-André Lafortune
@Marc-André:哎呀!我觉得它们是同一个东西,因为它们押韵了。 - Andrew Grimm
谢谢Marc-Andre指出这一点。我只是想说明你将“God”和块作为参数传递给“thank”,而不是将“God”作为参数传递给“proc”,并尝试将proc传递给上述问题中的“thank”。 - Nada Aldahleh
我在想我们是否可以以某种方式获取传递给该过程的参数?在这种情况下:在thank方法内部,我们能否访问传递给过程的name参数? - Masroor

3
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"

它能够正常运作,但我不太喜欢它。尽管如此,它确实帮助读者了解procs和blocks的使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接