How do I assign default values for two-dimensional

2019-07-01 15:03发布

I have a two-dimensional array created like this:

array = Array.new(10){Array.new(10)}

How can I assign default values for each cell on initialization?

I know I can do it with two nested each loops but I wondered if there is another way?

2条回答
走好不送
2楼-- · 2019-07-01 15:42

Two-dimensional array

To make your two-dimensional array, you can just do what kiddorails said:

array = Array.new(10) { Array.new(10, 4) }

Or you could do it this way:

array = 10.times.collect { [0] * 10 }

Bad two-dimensional array

While the following code is tempting (two people have tried to use it to answer this question) it is NOT the right way to make a two-dimensional array:

array = [[0] * 10] * 10  # BAD

This actually creates a single array with 10 zeroes, which is fine, but then it creates another array which just holds ten references to that array. The code above only creates two arrays!

Hash that acts like a two-dimensional array

Another more Ruby-like way to implement this data structure would be to use a hash and use x,y coordinate pairs as the keys. This is nice because it makes a location in the 2D array be a first-class object that you can easily pass around without having to worry about how exactly that location is represented. It becomes easier to iterate through every spot because you don't have to have nested loops, and that means it will probably be easier to duplicate the data. Also, Ruby's hash structure has a feature for letting you set a default value, so you don't have to do any tricky work to initialize the data.

Here is some example code showing the idea:

hash = {}
hash.default = 0
hash[[4,6]]      # => 0
hash[[4,6]] = 1
hash.inspect     # { [4, 6] => 1 }

You can also use your own custom-designed object for the hash keys if you want:

class Point < Struct.new(:x, :y)
end
hash = {}
hash.default = 0
hash[Point[4, 6]] = 1

Whatever you do, be careful to not modify any object you are using as a hash key, or else you will accidentally be modifying the data in the hash and actually screwing up the internal structure of the hash, requiring a rehash.

查看更多
\"骚年 ilove
3楼-- · 2019-07-01 15:49

Just supply a second argument with the value:

array = Array.new(10) { Array.new(10, 4) }

Here, the default value is 4 and thus, a 10*10 2D array is created with default value of 4.

查看更多
登录 后发表回答