How to pass parameters to a proc when calling it by a method?
13,143
Solution 1
I think the best way is:
def thank name
yield name if block_given?
end
Solution 2
def thank(arg, &block)
yield arg
end
proc = Proc.new do|name|
puts "Thank you #{name}"
end
Then you can do:
thank("God", &proc)
Solution 3
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.
Author by
Croplio
Updated on June 04, 2022Comments
-
Croplio almost 2 years
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 :)
-
David over 13 yearsYou should add 2 spaces before each line of code in order to make it a code sample in your answer. It will look prettier and add syntax highlighting to all your lines of code.
-
oligan over 13 years@Marc-André Lafortune: You're referring to the defining of
thank
, not the calling of it, right? -
Marc-André Lafortune over 13 years@Andrew: right, which is why I wrote that the
, &block
was not needed and not that the, &proc
was (that is needed) -
oligan over 13 years@Marc-André: Whoops! I think I read them as the same thing because they rhyme.
-
Nada Aldahleh over 13 yearsright, thanks Marc-Andre for pointing it out. I was just illustrating that you pass "God" and the block as arguments to thank, rather than passing "God" as an argument to proc, and passing proc to thank as been tried in the question above.