【问题标题】:How to pass parameters to a proc when calling it by a method?通过方法调用时如何将参数传递给proc?
【发布时间】:2011-03-25 07:59:10
【问题描述】:
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 ?

谢谢:)

【问题讨论】:

    标签: ruby parameters call block proc-object


    【解决方案1】:

    我认为最好的方法是:

    def thank name
      yield name if block_given?
    end
    

    【讨论】:

      【解决方案2】:
      def thank(arg, &block)
        yield arg
      end
      
      proc = Proc.new do|name|
         puts "Thank you #{name}"
      end
      

      那么你可以这样做:

      thank("God", &proc)
      

      【讨论】:

      • 您应该在每行代码之前添加 2 个空格,以使其成为您答案中的代码示例。它会看起来更漂亮,并为您的所有代码行添加语法突出显示。
      • @Marc-André Lafortune:你指的是thank的定义,而不是它的调用,对吧?
      • @Andrew:是的,这就是为什么我写道不需要, &block 而不是, &proc 是(需要)
      • @Marc-André:哎呀!我想我读它们是一样的,因为它们押韵。
      • 对,感谢 Marc-Andre 指出。我只是在说明您将“上帝”和块作为参数传递给感谢,而不是将“上帝”作为参数传递给 proc,然后将 proc 传递给thank,正如上面问题中所尝试的那样。
      【解决方案3】:

      与 Nada 提出的不同方式(相同,只是语法不同):

      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"
      

      它有效,但我不喜欢它。尽管如此,它将帮助读者了解如何使用过程和块。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-18
        相关资源
        最近更新 更多