2010-08-04 5 views
1
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 :)Comment passer des paramètres à un proc en l'appelant par une méthode? (Rubis)

Répondre

8

Je pense que la meilleure façon est:

def thank name 
    yield name if block_given? 
end 
7
def thank(arg, &block) 
    yield arg 
end 

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

Ensuite, vous pouvez faire:

thank("God", &proc) 
+0

Vous devez ajouter 2 espaces avant chaque ligne de code afin d'en faire un exemple de code dans votre réponse. Il semblera plus joli et ajoutera la syntaxe soulignant à toutes vos lignes de code. – David

+2

Pas besoin de ', & block' –

+0

@ Marc-André Lafortune: Vous parlez de la définition de« merci », pas de l'appel, n'est-ce pas? –

1

une autre façon:

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

def thank(proc_argument, name) 
    proc_argument.call(name) 
end 

thank(proc, "God") #=> "thank you God" 
thank(proc, "Jesus") #=> "thank you Jesus" 

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

Questions connexes