Como passar os parâmetros para um Proc ao chamá -lo por um método?
-
25-09-2019 - |
Pergunta
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 ?
Obrigado :)
Solução
Eu acho que a melhor maneira é:
def thank name
yield name if block_given?
end
Outras dicas
def thank(arg, &block)
yield arg
end
proc = Proc.new do|name|
puts "Thank you #{name}"
end
Então você pode fazer:
thank("God", &proc)
Uma maneira diferente do que a NADA propôs (é a mesma, apenas uma sintaxe 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, mas eu não gosto disso. No entanto, isso ajudará os leitores a entender como os procs e blocos são usados.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow