Frage

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 ?

Danke:)

War es hilfreich?

Lösung

Ich denke, der beste Weg ist:

def thank name
  yield name if block_given?
end

Andere Tipps

def thank(arg, &block)
  yield arg
end

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

Dann können Sie tun:

thank("God", &proc)

eine andere Art und Weise zu dem, was Nada vorgeschlagen (es ist das gleiche, nur anders 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"

Es funktioniert, aber ich weiß nicht wie es. Dennoch wird es Leser helfen zu verstehen, wie Procs und Blöcke verwendet werden.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top