Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I push an object to an array x amount of times with Ruby?

Tags:

arrays

ruby

If array = [1,2,3,4,5], how can I push the number 6, x amount of times to the array.

array.push(6) * x

When I run something like that it returns the entire array that was pushed 6, x amount of times. Putting parentheses around the push * x makes my code invalid, any suggestions?

Example:

array.push(6) "2 times" => [1,2,3,4,5,6,6]
like image 989
Lasonic Avatar asked Oct 11 '14 17:10

Lasonic


People also ask

How do you push an element to an array in Ruby?

The push() function in Ruby is used to push the given element at the end of the given array and returns the array itself with the pushed elements. Parameters: Elements : These are the elements which are to be added at the end of the given array. Returns: the array of pushed element.

How do you push the values of an object into an array?

The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.

What does .shift do in Ruby?

The shift() is an inbuilt function in Ruby returns the element in the front of the SizedQueue and removes it from the SizedQueue. Parameters: The function does not takes any element. Return Value: It returns the first element which is at the front of the SizedQueue and removes it from the SizedQueue.


1 Answers

Yes, You can using Array#fill method.

array = [1,2,3,4,5]
array.fill(12, array.size, 4)
# => [1, 2, 3, 4, 5, 12, 12, 12, 12]

Explanation

Suppose you have an array a = [1,2,3]. Now a.size will give you 3, where last index is 2. So, when you are using a.size with #fill, then you are telling to start pushing object from 3 to some n number of times.

like image 92
Arup Rakshit Avatar answered Oct 06 '22 09:10

Arup Rakshit