gpt4 book ai didi

ruby - super(&nil) 在 ruby​​ 中做什么?

转载 作者:数据小太阳 更新时间:2023-10-29 07:00:23 25 4
gpt4 key购买 nike

我正在阅读 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 => block 的情况下,它也可以将一些对象变成proc,例如:

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

Symbol#to_proc 产生如下相同的功能

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

我不确定这方面的官方文档在哪里(欢迎指点),但从测试看来 &nil 实际上根本没有将任何 block 传递给该方法 - 它有没有效果:

def a
block_given?
end

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

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

如果你用 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

问题是,虽然您可以阻止传递位置和关键字参数,但这种方法不会阻止传递 block :

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。它本质上是在说“什么都不传递”。我想如果您不这样做,那么 block 会自动转发。

关于ruby - super(&nil) 在 ruby​​ 中做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50670794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com