1

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?

2 Answers 2

5

Array#product is the method you're looking for:

(1..4).to_a.product (1..2).to_a
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.