0

So I am trying to build a multidimensional array by starting with a single array and splitting it into separate arrays to account for possible added values.

Example:

Original Array: [2,3]

adding either 4 or 5

New array: [[2,3,4],[2,3,5]]

I have tried the following:

array=[2,3]
array1=array<<4
array2=array<<5

array=[2,3]
array1=array<<4
array.pop
array2=array<<5

array=[2,3]
array1=array.push 4
array.pop
array2=array.push 5

The results I get are:

[[2,3,4,5],[2,3,4,5]]
[[2,3,5],[2,3,5]]
[[2,3,5],[2,3,5]]

Is there a way to alter the original array only in the new variables so that the variables don't end up equal when I combine them?

1
  • 1
    array1 = array + [4]; array2 = array + [5] Commented Dec 8, 2014 at 19:37

3 Answers 3

1

There are a number of methods on Array that are in-place modifiers, that is they don't make copies, and << is one of them.

What you might find easier is this:

array = [ 2, 3 ]
array1 = array + [ 4 ]
array2 = array + [ 5 ]

The result in this case is two independent arrays.

Sign up to request clarification or add additional context in comments.

Comments

1

Another interesting way to do this is using the splat operator:

array = [2, 3]
array1 = [*array, 4]
# => [2, 3, 4]
array2 = [*array, 5]
# => [2, 3, 5]

1 Comment

...which lends itself nicely to mapping an array of values to add to array. Nice.
0

If you have several times to add to:

array = [1, 2, 3]

say:

b = [*(4..20)]
  #=> [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

you could use the method Array#product:

[array].product(b).map(&:flatten)
  #=> [[1, 2, 3,  4], [1, 2, 3,  5], [1, 2, 3,  6], [1, 2, 3,  7],
  #    [1, 2, 3,  8], [1, 2, 3,  9], [1, 2, 3, 10], [1, 2, 3, 11],
  #    [1, 2, 3, 12], [1, 2, 3, 13], [1, 2, 3, 14], [1, 2, 3, 15],
  #    [1, 2, 3, 16], [1, 2, 3, 17], [1, 2, 3, 18], [1, 2, 3, 19],
  #    [1, 2, 3, 20]]

1 Comment

Thanks, that may be helpful I will have to play with the #product method to make sure I understand it.

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.