More than 5 years have passed since last update.
10 * 10 の二次元配列をRubyで作る。
size = 10
([[nil] * size] * size).map(&:clone)
最初、こういうコードを書いたけど、すべての行が同じ配列を参照することになるのでcloneしないといけないとか、そもそも読みにくいとかダサさを感じたので、
size = 10
Array.new(size ** 2).each_slice(size).to_a
こう、とか?
size = 10
Array.new(size) { Array.new(size) }
これが一番素直な気もしたりした。
ちなみにRubyには matrix と言う標準添付ライブラリがあるので
require 'matrix'
Matrix.zero(10).to_a
とかでも同じようなものができる。nil埋めじゃなくて0埋めだけど。
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
