【问题标题】:Should I specify &block argument in def?我应该在 def 中指定 &block 参数吗?
【发布时间】:2014-05-28 16:08:27
【问题描述】:

在 Ruby 中,指定您的方法采用 &block 是否更好(样式?)?

只要方法主体包含yield,选择似乎只是样式问题。

例如,给定:

def abc1(a, c)
  puts a
  yield
  puts c
end

def abc2(a, c, &block)
  puts a
  yield
  puts c
end

以下两个调用:

abc1('a', 'c') { puts 'b' }
abc2('a', 'c') { puts 'b' }

每次打印并返回相同的东西:

a
b
c
=> nil

那么,如果真的只是风格问题,那么惯例(或更好的风格)是什么?

【问题讨论】:

    标签: ruby coding-style arguments block function


    【解决方案1】:

    使用您当前的代码,第一个更好。当您使用yield 时,无需使用&block,因为它是隐式。但是,是的,要提醒一件事,使用yield 时必须传递一个块,否则会出现错误。尽管可以使用block_given? 处理该错误。

    Ruby 的yield 语句将控制权交给方法主体中用户指定的块。所以,如果你再次使用&block,它是多余的,所以不需要使用它。

    【讨论】:

      【解决方案2】:

      重要的是要记住,将块作为参数传递的主要原因是它被转换为对象(Proc 类的实例),因此可以传递:

      def ab(&block)
        yield "ab"
        cd(&block)
      end
      
      def cd(&block)
        yield "cd"
        block.call("cd")
      end
      
      ab { |str| puts "In #{str}. Please pass the salt, the pepper and the proc." }
      In ab. Please pass the salt, the pepper and the proc.
      In cd. Please pass the salt, the pepper and the proc.
      In cd. Please pass the salt, the pepper and the proc.
      

      【讨论】:

        【解决方案3】:

        这是个人品味的问题。常见的两种情况如下:

        def abc1(a, c)
          puts a
          yield
          puts c
        end
        

        通常yield 用于隐式传递块时,如本例所示。另一个你常见的就是

        def abc2(a, c, &block)
          puts a
          block.call(args)
          puts c
        end
        

        这样做的好处是阅读您的代码的人可以很容易地看到需要传递一个块。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-10-11
          • 2012-03-05
          • 2012-02-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多