Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove outer array from a nested array?

Tags:

ruby

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.

like image 370
MrPizzaFace Avatar asked Dec 02 '22 17:12

MrPizzaFace


2 Answers

Don't use <<, use +

arr = [13,12,31,31]

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

# arr => [13,12,31,31,12,13,54,32]
like image 76
meagar Avatar answered Feb 19 '23 10:02

meagar


You should use Array#flatten

[[13,12,31,31,12,13,54,32]].flatten # => [13, 12, 31, 31, 12, 13, 54, 32]
like image 25
bjhaid Avatar answered Feb 19 '23 11:02

bjhaid