为什么这个 Ruby 每个循环不会中断?
我的一个个人项目中有以下代码:
def allocate(var, value) # Allocate the variable to the next available spot.
@storage.each do |mem_loc|
if mem_loc.free?
mem_loc.set(var, value) # Set it then break out of the loop.
break
end
end
end
存储数组中的每一项都是一个响应 free? 的对象。并设置。我想做的是循环遍历数组,寻找下一个空闲(空)对象来设置变量。我的问题是,这只是循环遍历每个对象并设置它们。我是否错误地使用了break函数?
测试它,我调用以下内容:
store.allocate(:a, 10)
store.allocate(:b, 20)
因此 store[1] 应该设置为 :b 和 20。但是当我输出内容时,它的值是 10,数组的其余部分也是如此。
I have the following code in one of my personal projects:
def allocate(var, value) # Allocate the variable to the next available spot.
@storage.each do |mem_loc|
if mem_loc.free?
mem_loc.set(var, value) # Set it then break out of the loop.
break
end
end
end
Each item in the storage array is an object that responds to free? and set. What I am trying to do is cycle through the array, looking for the next free (empty) object to set the variable to. My problem is, this just cycles through every object and sets them all. Am I using the break function incorrectly?
Testing it, I call the following:
store.allocate(:a, 10)
store.allocate(:b, 20)
So store[1] should be set to :b and 20. But when I output the contents, it's value is 10, as is the rest of the array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信我已经找到了错误,但它实际上并不在上面的代码中。
当我设置存储阵列时,我确实是这样的:
相信它会创建 1000 个不同的对象。我认为实际发生的情况是,它创建了 1000 个对同一个对象的引用,所以当我更改其中一个时,我更改了所有它们。我可以通过在两个不同的数组位置上使用 put 方法来证明这一点,并且它们都返回:
I believe I have found the mistake, and it wasn't actually in the code above.
When I set up the storage array, I did like so:
Believing it would create 1000 different objects. What I think actually happened, was that it created 1000 references to the same object, so when I changed one of them, I changed all of them. I could prove this by using the puts method on two different array locations, with both of them returning: