gpt4 book ai didi

arrays - Ruby Koans - 数组填充方法会影响它的返回方式

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

我一直在研究 Ruby Koans,但我已经到了我不太了解的部分。具体来说,就是about_dice_project,他们要求我们定义一个类来通过几个预先设定的测试。本来,我的类(class)看起来像

class DiceSet
attr_accessor :values
def initialize
@values = []
end
def roll(num)
num.times { |i| @values[i] = rand(1..6) }
return @values
end
end

但这没有通过下面的测试

dice = DiceSet.new

dice.roll(5)
first_time = dice.values

dice.roll(5)
second_time = dice.values

assert_not_equal first_time, second_time,
"Two rolls should not be equal"

经过一些测试后我意识到 first_time 和 second_time 具有相同的 object_id。所以我在 stackoverflow 上寻求帮助,发现 this answer ,它没有直接回答我的问题,但我确实发现我们的代码存在重大差异;即,不是使用“num.times”掷骰子的方式,而是使用

@values = Array.new(num) { rand(1..6) }

这确实通过了上述测试。

找到这个之后,我试图弄清楚为什么我的原始代码不起作用,所以我想也许 Ruby 是通过引用传递的,这就是为什么当掷骰子方法创建一个新数组而不是修改现有数组,这是创建的新对象 ID。但后来我发现this question ,它表示 Ruby 是按值传递的,如果是这种情况,那么我原以为我原来的方法会奏效。

所以我现在又糊涂了,想问一下——我的思路哪里错了? Ruby 是否仅在某些情况下按值传递?我是否误解了按值传递/引用甚至意味着什么?我的问题与按值传递/引用完全无关吗?

最佳答案

您可以将 ruby​​ 中的对象视为对数据的引用。因此,即使 Ruby 是按值传递,得到副本的是对象,也就是下划线数据的句柄。

即使从您链接到的答案中也说过:

Variables are always references to objects. In order to get an object that won't change out from under you, you need to dup or clone the object you're passed, thus giving an object that nobody else has a reference to. (Even this isn't bulletproof, though — both of the standard cloning methods do a shallow copy, so the instance variables of the clone still point to the same objects that the originals did. If the objects referenced by the ivars mutate, that will still show up in the copy, since it's referencing the same objects.)

关于arrays - Ruby Koans - 数组填充方法会影响它的返回方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45758124/

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