Reputation: 7210
Is it possible to create the following 2d array dynamically:
[[1, 1], [1, 2], [2, 1], [2, 2], [3, 1], [3, 2], [4, 1], [4, 2]]
Eg.
(1..4).to_a
#=> [1, 2, 3, 4]
(1..2).to_a
#=> [1, 2]
Combine this somehow?
Upvotes: 1
Views: 220
Reputation:
Array#product is the method you're looking for:
(1..4).to_a.product (1..2).to_a
Upvotes: 5
Reputation: 3772
This sounds a bit like a homework question. It would be nice to get context around what you're trying to do. You'll want to spend some time researching the different loops/iterators that ruby provides you. Here is a method that will return the array you're looking for by using one of ruby's iterator methods upto
.
def generate_array
arr = []
1.upto(4) do |y|
1.upto(2) do |x|
arr << [y, x]
end
end
arr
end
Upvotes: 0