gpt4 book ai didi

ruby - 在一行中实例化两个实例时出现意外的 Ruby 行为

转载 作者:太空宇宙 更新时间:2023-11-03 17:31:46 25 4
gpt4 key购买 nike

我创建了一个为每个实例生成不同名称的类,但是在一个语句中实例化两个实例时测试意外失败。

这是类。

class Robot
attr_accessor :name
@@current_name = 'AA000'
def initialize
@name = @@current_name
@@current_name.next!
end
end

这里类的行为符合预期

irb(main):009:0> Robot.new.name
=> "AA001"
irb(main):010:0> Robot.new.name
=> "AA002"

这是意外行为,我原以为是 false。此代码正在对我试图通过的练习进行测试,因此我无法更改测试。

irb(main):011:0> Robot.new.name == Robot.new.name
=> true

检查 object_id 显示正在创建两个不同的实例。

irb(main):012:0> Robot.new.object_id == Robot.new.object_id
=> false

为什么 Ruby 会这样做,我应该怎么做才能修复它 & 假设有一个术语,我可以在搜索中输入什么来找到关于这个问题的答案。

最佳答案

看看这是否有帮助:

class Robot
attr_accessor :name

@@current_name = 'AA000'

def initialize
@name = @@current_name
@@current_name.next!
end
end

x = Robot.new
puts x.name
y = Robot.new
puts y.name

puts x.name == y.name
puts x.name
puts y.name

--output:--
AA001
AA002
true
AA002
AA002

Why is Ruby doing this

因为每个实例的 @name 变量引用与变量 @@current_name 相同的字符串,并且您不断地用 ! 更改该字符串> 方法。

what should I do to fix it

class Robot
attr_accessor :name

@@current_name = 'AA000'

def initialize
@name = @@current_name.dup
@@current_name.next!
end
end


x = Robot.new
puts x.name
y = Robot.new
puts y.name

p x.name == y.name
p x.name
p y.name

--output:--
AA000
AA001
false
AA000
AA001

尽管如此,我和许多其他人会警告您永远不要在您的代码中使用 @@variables

Ruby 赋值运算符:

1. x = “hello”:

x ------> “hello”


2. y = x:

x ------> “hello”
^
|
y -----------+


3. y << “ world”:


x ------> “hello world”
^ ^
| ^
y -----------+ ^
> > >

x 和 y 的名字可以拼写为 @name@@current_name 并不重要。

这是另一个代码示例:

x = "hello"
y = x
y << " world"

puts x, y

--output:--
hello world
hello world


x.next!
puts x, y

--output:--
hello worle
hello worle

这是一个不可变类型的例子:

1. x = 10:

x ------> 10


2. y = x:

x ---------> 10
^
|
y -----------+


3. y += 1
=> y = y + 1
=> y = 10 + 1
And 10 + 1 creates the new Integer object 11 and assigns it to y:


x ------> 10

y ------> 11

表达式 10 + 1 不会递增 x 和 y 都引用的 Integer 对象 10——因为 Integer 对象是不可变的。

这是另一个例子:

x = 10
y = x

x.next
puts x,y #=> ??

x.next创建了一个新的Integer对象11,由于新创建的Integer对象11没有赋值给变量,11被丢弃了,所以x和y仍然引用同一个Integer对象10。

关于ruby - 在一行中实例化两个实例时出现意外的 Ruby 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33592985/

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