Skip to content

Instantly share code, notes, and snippets.

@undecided
Created December 21, 2013 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save undecided/8071690 to your computer and use it in GitHub Desktop.
Save undecided/8071690 to your computer and use it in GitHub Desktop.
Answer to the question: how to initialise a multi-dimensional array, filled with nils, in ruby?
# My answer at the time was to do something like this
[[nil]*3]*4
#=> [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
# The next question was whether I knew some initializer to do that for us.
# Apparently, there is:
Array.new(4) { Array.new(3) }
#=> [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
# But that wasn't the brainwave my brain came up with just now.
# There's a Matrix class!
require 'matrix' # it's in the standard library, so no gems required
Matrix.build(3,4) {nil}.to_a
#=> [[nil, nil, nil, nil], [nil, nil, nil, nil], [nil, nil, nil, nil]]
# Of course, that's build(rows, columns). If you wanted x,y you could use:
Matrix.build(3,4) {nil}.to_a.transpose
#=> [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
# or just switch them around yourself.
# My original answer was more succinct I think :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment