VOOZH about

URL: https://qiita.com/udzura/items/1b3ed48b8b6363ca87b2

⇱ 二次元配列@Ruby #Ruby - Qiita


👁 Image
5

Go to list of users who liked

4

Share on X(Twitter)

Share on Facebook

Add to Hatena Bookmark

More than 5 years have passed since last update.

@udzura(Uchio KONDO)in👁 Image
GMOペパボ株式会社

二次元配列@Ruby

5
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

Go to list of users who liked

4
2

Go to list of comments

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

Go to list of users who liked

4