如何通过一个方法调用时,它的参数传递给PROC?
-
25-09-2019 - |
题
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 ?
感谢:)
解决方案
我认为最好的方法是:
def thank name
yield name if block_given?
end
其他提示
def thank(arg, &block)
yield arg
end
proc = Proc.new do|name|
puts "Thank you #{name}"
end
然后,你可以这样做:
thank("God", &proc)
以不同的方式是什么纳达提出的(这是一样的,只是不同的语法):
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"
它的工作原理,但我不喜欢它。尽管如此,它有助于读者了解如何使用特效和块。
不隶属于 StackOverflow