Как передать параметры в процесс при вызове его методом? - PullRequest
8 голосов
/ 04 августа 2010
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 ?

Спасибо:)

Ответы [ 3 ]

13 голосов
/ 04 августа 2010

Я думаю, что лучший способ это:

def thank name
  yield name if block_given?
end
8 голосов
/ 04 августа 2010
def thank(arg, &block)
  yield arg
end

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

Тогда вы можете сделать:

thank("God", &proc)
2 голосов
/ 23 сентября 2016

другой способ, который предложил Нада (тот же самый, просто другой синтаксис):

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"

Это работает, но мне это не нравится.Тем не менее, это поможет читателям понять, КАК используются процедуры и блоки.

...