9
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 :)

ian
  • 12,003
  • 9
  • 51
  • 107
Croplio
  • 3,433
  • 6
  • 31
  • 37

3 Answers3

13

I think the best way is:

def thank name
  yield name if block_given?
end
Daniel O'Hara
  • 13,307
  • 3
  • 46
  • 68
9
def thank(arg, &block)
  yield arg
end

proc = Proc.new do|name|
   puts "Thank you #{name}"
end

Then you can do:

thank("God", &proc)
Nada Aldahleh
  • 1,298
  • 14
  • 15
  • You 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. – David Aug 04 '10 at 15:50
  • @Marc-André Lafortune: You're referring to the defining of `thank`, not the calling of it, right? – Andrew Grimm Aug 04 '10 at 23:31
  • @Andrew: right, which is why I wrote that the `, &block` was not needed and not that the `, &proc` was (that is needed) – Marc-André Lafortune Aug 05 '10 at 05:09
  • @Marc-André: Whoops! I think I read them as the same thing because they rhyme. – Andrew Grimm Aug 05 '10 at 06:23
  • right, 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. – Nada Aldahleh Aug 05 '10 at 14:25
  • just wondering if we can somehow get our hands on the arguments passed to that proc? in this case: inside the `thank` method can we access the `name` argument that is passed to the proc? – Masroor Aug 13 '22 at 04:33
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.

BenKoshy
  • 33,477
  • 14
  • 111
  • 80