gpt4 book ai didi

Ruby:为什么 'while (p || (p=exns.shift))' 与 'while p ||= exns.shift' 不同?

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

这是怎么回事?我看不出这两个片段的行为有何不同,但它们确实如此。

完整代码,尝试其中一个:

class T
def initialize
@e=[4,2]
end
def shift
r=@e.shift
puts "[#{r.inspect}]"
r
end
end

exns=T.new

while (p || (p=exns.shift))
#while p ||= exns.shift
puts "p: #{p.inspect}"
p -= 1
p=nil if p<1
puts " #{p.inspect}"
puts "T" if p
end

'while (p || (p=exns.shift))' 似乎永远不会因为某种原因而短路。我想知道原因。

最佳答案

您的问题出在您选择命名变量的字母 - p 与其他字母(例如 q)不同,因为它也是内核的名称方法 p() :

p
# => nil
q
# NameError: undefined local variable or method `q' for main:Object

因此,因为您没有在 while 循环之前定义局部变量名称 p,所以它实际上是仅在循环范围内声明的。 p>

要了解这有多重要,只需在循环之前添加以下行:

p = nil

现在,两个选项的作用相同。

关于Ruby:为什么 'while (p || (p=exns.shift))' 与 'while p ||= exns.shift' 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25154144/

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