Ruby:为什么所有坐标都在数组数组中更新? [英] Ruby: Why are all coordinates getting updated in an array of arrays?

查看:36
本文介绍了Ruby:为什么所有坐标都在数组数组中更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改特定坐标,但数组正在全部更新.

I'm trying to change a specific coordinate, but an array is getting all updated.

目标是将 fixed 属性更改为单个坐标.

The goal is to change the fixed attribute to a single coordinate.

class Case
  attr_accessor :fixed

  def initialize
    self.fixed = false
  end

  def fixed?
    !!fixed
  end
end

def display(arr)
  5.times do |x|
    5.times do |y|
      print arr[x][y].fixed?
      print ' '
    end

    puts
  end
end

# Defining array
arr = Array.new(5){ Array.new(5, Case.new) }

# Displaying the arrays
display(arr)

# Changing value of a single coord
arr[2][3].fixed = true

# Displaying the arrays
display(arr)

这是第一次显示调用的结果

Here is the result for the first display call

false false false false false 
false false false false false 
false false false false false 
false false false false false 
false false false false false 

第二个显示器

false false false false false 
false false false false false 
true true true true true 
false false false false false 
false false false false false 

预期结果是:

false false false false false 
false false false false false 
false false false true false 
false false false false false 
false false false false false 

推荐答案

问题是您在行中多次放置同一个实例.要使数组中的每个项目成为新对象,请将数组定义更改为以下内容:

The problem is that you are placing the same instance in the row multiple times. To make each item in the array a new object change your array definition to the following:

arr = Array.new(5){ Array.new(5) {Case.new}   }

有关详细信息,请参阅此问题:如何创建对象数组?

See this question for more info: How to create array of objects?

这篇关于Ruby:为什么所有坐标都在数组数组中更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆