5

If I have the following arr = [13,12,31,31] Now say I want to push in another set of numbers like 12,13,54,32

So I can do arr << [12,13,54,32] but now I have [13,12,31,31,[12,13,54,32]]

So how can I remove the outside array? arr = arr.pop works sometimes but I'm guessing that a better way exists. Please enlighten.

2
  • 3
    arr << [12,13,54,32] would result in [13, 12, 31, 31, [12, 13, 54, 32]], not [[13,12,31,31,12,13,54,32]]. Is that just a typo? Commented Jan 17, 2014 at 2:45
  • @matt fixed that typo thanks! Commented Jan 17, 2014 at 2:48

3 Answers 3

10

Don't use <<, use +

arr = [13,12,31,31]

arr +=  [12,13,54,32]

# arr => [13,12,31,31,12,13,54,32]
Sign up to request clarification or add additional context in comments.

1 Comment

Or concat to avoid creating a new array.
8

You should use Array#flatten

[[13,12,31,31,12,13,54,32]].flatten # => [13, 12, 31, 31, 12, 13, 54, 32]

Comments

2

You have a couple options. You could join your arrays using the + operator and not have to deal with the outer array. If you have an outer array and want to flatten it, simply call flatten on the array. As matt mentioned in the comments above, you can also use concat.

# Creates a new array
[13,12,31,31] + [12,13,54,32]
=> [13, 12, 31, 31, 12, 13, 54, 32]

# Creates a new array, unless you use flatten!
[13, 12, 31, 31, [12, 13, 54, 32]].flatten
=> [13, 12, 31, 31, 12, 13, 54, 32]

# Modifies the original array
[13,12,31,31].concat([12,13,54,32])
=> [13, 12, 31, 31, 12, 13, 54, 32]

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.