Cómo pasar parámetros a un proc al llamarlo por un método?
-
25-09-2019 - |
Pregunta
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 ?
Gracias:)
Solución
creo que la mejor manera es:
def thank name
yield name if block_given?
end
Otros consejos
def thank(arg, &block)
yield arg
end
proc = Proc.new do|name|
puts "Thank you #{name}"
end
A continuación, puede hacer:
thank("God", &proc)
una manera diferente a lo que propuso Nada (que es la misma sintaxis, sólo diferente):
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"
Funciona, pero no me gusta. No obstante que ayudará a los lectores a comprender cómo se utilizan los procs y bloques.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow