Created
December 21, 2013 16:35
-
-
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?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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