Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add multiple elements to an array?

Tags:

arrays

ruby

I can easily add one element to an existing array:

arr = [1]
arr << 2
# => [1, 2]

How would I add multiple elements to my array?

I'd like to do something like arr << [2, 3], but this adds an array to my array #=> [1, [2, 3]]

like image 740
davegson Avatar asked Dec 19 '13 15:12

davegson


People also ask

How do you add multiple data to an array in Java?

If you want to add multiple elements to the array at once, you can think of initializing the array with multiple elements or convert the array to ArrayList. ArrayList has an 'addAll' method that can add multiple elements to the ArrayList.

Can I add elements to an array?

If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().


3 Answers

Using += operator:

arr = [1] arr += [2, 3] arr # => [1, 2, 3] 
like image 182
falsetru Avatar answered Sep 21 '22 20:09

falsetru


Make use of .push

arr = [1] arr.push(2, 3) # => [1, 2, 3] 

You can also .push() all elements of another array

second_arr = [2, 3] arr.push(*second_arr) # => [1, 2, 3] 

But take notice! without the * it will add the second_array to arr.

arr.push(second_arr) # => [1, [2, 3]] 

Inferior alternative:

You could also chain the << calls:

arr = [1] arr << 2 << 3 # => [1, 2, 3] 
like image 20
davegson Avatar answered Sep 22 '22 20:09

davegson


You can do also as below using Array#concat:

arr = [1]
arr.concat([2, 3]) # => [1, 2, 3]
like image 24
Arup Rakshit Avatar answered Sep 20 '22 20:09

Arup Rakshit