超级(&nil)在ruby中做什么?
发布时间:2020-12-17 04:15:49 所属栏目:百科 来源:网络整理
导读:我正在阅读 the source code for concurrent-ruby,并遇到了这行ruby代码. def initialize(*args,block) super(nil) # --- ??? synchronize { ns_initialize(*args,block) }end 有人可以向我解释它应该做什么吗? 解决方法 你必须先了解这里使用的运算符.参见
我正在阅读
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.它本质上是在说“不作为一个块”.我想如果你不这样做,那么块会自动转发. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |