方法でそれを呼び出すとき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"
これは動作しますが、私はそれが好きではありません。それにもかかわらず、読者がprocsのとブロックが使用されている方法を理解するのに役立ちます。
所属していません StackOverflow