超级(&nil)在ruby中做什么?

我正在阅读 the source code for concurrent-ruby,并遇到了这行ruby代码.
def initialize(*args,&block)
  super(&nil) # <--- ???
  synchronize { ns_initialize(*args,&block) }
end

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

解决方法

你必须先了解&这里使用的运算符.参见例如:
# 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 =>中块情况下,它还能够将一些对象转换为procs,例如:

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

符号#to_proc产生如下相同的功能

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

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

def a
  block_given?
end

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

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

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

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.它本质上是在说“不作为一个块”.我想如果你不这样做,那么块会自动转发.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...