super(& nil)在红宝石中做了什么?

时间:2018-06-03 20:43:02

标签: ruby

我正在阅读the source code for concurrent-ruby,并遇到了这行红宝石代码。

def initialize(*args, &block)
  super(&nil) # <--- ???
  synchronize { ns_initialize(*args, &block) }
end

有人可以向我解释它应该做什么吗?

1 个答案:

答案 0 :(得分:3)

您必须首先了解此处使用的&运算符。例如见:

# The & here converts a block argument to a proc
def a(&blk)
end

# The & here converts the proc to a block
a(&Proc.new { true })

在proc =&gt;中块情况下,它还能够将一些对象转换为过程,例如:

# The symbol :class gets to_proc called here
[1].map(&:class)

Symbol#to_proc产生与以下相同的功能

[1].map(&Proc.new { |x| x.class })

我不确定这个官方文档在哪里(会欢迎指针),但是从测试来看似乎&nil实际上并没有将任何块传递给方法 - 它没有效果:

def a
  block_given?
end

a {} # => true
a &:puts # => true
a &nil # => false

现在已经解释了,我可以继续说明为什么需要它。

如果省略super的parens,则传递所有参数:

class A
  def initialize arg
    puts arg && block_given?
  end
end

class B < A
  def initialize arg
    super
  end
end

B.new(1) {}
# prints "true" - block and arg were both passed to super

如果您不希望发生这种情况,可以手动将参数传递给super。这有一个问题,我将在之后得到:

class A
  def initialize arg1, arg2=nil
    puts arg1 && !arg2
  end
end

class B < A
  def initialize arg1, arg2=nil
    super arg1
  end
end

B.new 1, 2
# prints "true" - arg1 was passed to super but not arg2

问题是虽然你可以防止传递位置和关键字args,但这种方法不会阻止传递一个块:

class A
  def initialize arg1
    puts arg1 && block_given?
  end
end

class B < A
  def initialize arg1
    super arg1
  end
end

B.new(1) { }
# prints "true" - arg and block were both passed

无论出于何种原因,重要的是它不会发生,所以他们使用我以前从未见过的成语,但似乎完成了工作:&nil。它本质上是在说“不作为一个块”。我想如果你不这样做,那么会自动转发块。