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 ?

Merci:)

Était-ce utile?

La solution

Je pense que la meilleure façon est:

def thank name
  yield name if block_given?
end

Autres conseils

def thank(arg, &block)
  yield arg
end

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

Ensuite, vous pouvez faire:

thank("God", &proc)

une façon différente de ce que Nada a proposé (c'est la même, la syntaxe juste différente):

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"

Il fonctionne, mais je ne l'aime pas. Néanmoins, il aidera les lecteurs à comprendre comment procs et les blocs sont utilisés.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top