views:

52

answers:

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

+2  A: 

I think the best way is:

def thank name
  yield name if block_given?
end
floatless
+2  A: 
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
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
Marc-André Lafortune
@Marc-André Lafortune: You're referring to the defining of `thank`, not the calling of it, right?
Andrew Grimm
Marc-André Lafortune
@Marc-André: Whoops! I think I read them as the same thing because they rhyme.
Andrew Grimm
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