How to pass parameters to a proc when calling it by a method?
-
25-09-2019 - |
Question
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 ?
Thanks :)
Solution
I think the best way is:
def thank name
yield name if block_given?
end
OTHER TIPS
def thank(arg, &block)
yield arg
end
proc = Proc.new do|name|
puts "Thank you #{name}"
end
Then you can do:
thank("God", &proc)
a different way to what Nada proposed (it's the same, just different syntax):
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"
It works, but I don't like it. Nevertheless it will help readers understand HOW procs and blocks are used.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow