Not logged inGosu Forums
Forum back to libgosu.org Help Search Register Login
Up Topic Gosu / Gosu Exchange / Ruby does not want to create a new object
- - By Andrek Date 2015-07-12 19:10 Edited 2015-07-12 19:28
Hi everyone! i'm back with Ruby/Gosu from almost 2 year and i have a problem with ruby, first i dont speak very english then i'm confused about where i can post this.

I try to make a data class like this:

@data = Array.new(width, Array.new(height, default_value))

but when i want to change a value like this:

@data[x][y] = terrain_id

No only change that coordinate, Ruby change all coordinate Y in X coordinate, example:


@data[0][1] = 0 # [
[nil, 1, nil], # XY: 0, 1
[nil, 1, nil], # XY: 1, 1
[nil, 1, nil] # XY: 2, 1
]


The problem is that all arrays have the same object_id. I can't understand why, please help me!

Data Class Completed
class Data_Tilemap
  attr_reader(:data)
  attr_accessor(:default_value)
  def initialize(width, height, default_value = 0)
    @width = width
    @height = height
    @default_value = default_value
    #@data = Array.new(width, Array.new(height, default_value))
    @data = []
    width.times { @data.push(Array.new) }
  end
  def [](x, y)
    if x.between?(0, @width - 1) and y.between?(0, @height - 1)
      return @data[x][y]
    else
      return @default_value
    end
  end
  def []=(x, y, value)
    @data[x][y] = value if x.between?(0, @width - 1) and y.between?(0, @height - 1)
    print(
    @data[0].object_id, " ", #=> 21483444
    @data[1].object_id, " ", #=> 21483444
    @data[2].object_id) #=> 21483444
    puts
  end
  def resize(width, height)
    new_data = Array.new(width, Array.new(height, @default_value))
    for x in 0...@width
      for y in 0...@height
        if x.between?(0, width - 1) and y.between?(0, height - 1)
          new_data[x][y] = @data[x][y]
        end
      end
    end
    @data = new_data
    @width = width
    @height = height
  end
end


Edit:

Important information: i save the data like this:
file = File.open(filename, "wb")
Marshal.dump(data, file)
file.close


and load:

file = File.open(@filename, "rb")
@data = Marshal.load(file)
file.close
Parent - - By jlnr (dev) Date 2015-07-13 07:20
Re:

@data = Array.new(width, Array.new(height, default_value))

When you pass a second argument to Array#initialize, it will be evaluated once (like all method arguments) and used as the initial value in the array. If you pass a block, however, that block will be evaluated once to generate the initial value for each cell:

@data = Array.new(width) { Array.new(height, default_value) }
Parent - By Andrek Date 2015-07-13 14:36
It's work! thanks a lot, i can understand the operation. Now i can continue with my project, ty!
Up Topic Gosu / Gosu Exchange / Ruby does not want to create a new object

Powered by mwForum 2.29.7 © 1999-2015 Markus Wichitill