Reputation: 2322
I want to fill a two dimensional array with certain values. I want to get:
[
['Num00', 'Num01', 'Num02'],
['Num10', 'Num11', 'Num12'],
['Num20', 'Num21', 'Num22']
]
How can I do it?
This is my code:
game_field = Array.new(3, Array.new(3))
3.times do |i|
3.times do |j|
game_field[i][j] = 'Num' + i.to_s + j.to_s
end
end
game_field
Upvotes: 0
Views: 126
Reputation: 37507
Just a note that building a Matrix
is simple because it has an inherent notion of rows and columns:
Matrix.build(3){|i,j| "Num#{i}#{j}"}
I think the Matrix class is often overlooked. The built-in methods to operate on rows, columns, submatrices, etc, can sometimes be really handy.
Upvotes: 3
Reputation: 9497
Well using Eric and Sawa's answer along with repeated_permutation
we have
[0,1,2].repeated_permutation(2)
.map { |a, b| "Num#{a}#{b}" }
.each_slice(3).to_a
Upvotes: 0
Reputation: 80065
Ternary numbers?
(0...9).map{|n| "Num#{n.to_s(3).rjust(2,"0")}"}.each_slice(3).to_a
Upvotes: 1
Reputation: 47472
you can also try
game_field = (0..2).map do |i|
(0..2).map do |j|
"Num#{i}#{j}"
end
end
One liner
game_field = (0..2).map {|i| (0..2).map {|j| "Num#{i}#{j}"} }
Upvotes: 1
Reputation: 121000
Just out of curiosity:
([(?0..?2)] * 2).
map(&:to_a).
reduce(:product).
each_slice(3).
map { |e| e.map(&:join).map(&'Num'.method(:+)) }
Upvotes: 2
Reputation: 54223
Array.new
accepts a block in which you can define the element directly:
Array.new(3){|i| Array.new(3){|j| "Num#{i}#{j}" } }
# [["Num00", "Num01", "Num02"], ["Num10", "Num11", "Num12"], ["Num20", "Num21", "Num22"]]
When you call Array.new(3, Array.new(3))
, you create an array which contains 3 times the exact same object : Array.new(3)
. When you modify an element in an inner-array, you modify it on every array!
If you initialize game_field
like this : game_field = Array.new(3){ Array.new(3) }
, your code works fine.
Upvotes: 6