Domanda

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 ?

Grazie:)

È stato utile?

Soluzione

Penso che il modo migliore è:

def thank name
  yield name if block_given?
end

Altri suggerimenti

def thank(arg, &block)
  yield arg
end

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

Poi si può fare:

thank("God", &proc)

un modo diverso di quello che Nada ha proposto (che è lo stesso, la sintassi solo diverso):

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"

Funziona, ma non mi piace. Tuttavia sarà aiutare i lettori a capire come vengono utilizzati proc e blocchi.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top