Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.