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]
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.
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.
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.
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]
. Nowa.size
will give you3
, where last index is2
. So, when you are usinga.size
with#fill
, then you are telling to start pushing object from3
to somen
number of times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With