How do I push an object to an array x times in Ruby?
If array = [1,2,3,4,5]
, how can I type the number 6
, the x
number of times in array
.
array.push(6) * x
When I start something like this, it will return the entire array, which has been pressed 6
, x
the number of times. Putting parentheses around push * x
makes my code invalid, any suggestions?
Example:
array.push(6) "2 times" => [1,2,3,4,5,6,6]
source to share
Yes, you can use the 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
Let's assume you have an array
a = [1,2,3]
. Nowa.size
will give you3
where the last index is2
. So, when you usea.size
with#fill
, then you are talking to start pushing the object out3
severaln
times.
source to share