LoginSignup
5
4

More than 5 years have passed since last update.

二次元配列@Ruby

Last updated at Posted at 2013-09-16

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埋めだけど。

5
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4