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]
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.
It works:
irb(main):001:0> a = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
irb(main):002:0> a += [6] * 2
=> [1, 2, 3, 4, 5, 6, 6]
As an alternative:
irb(main):003:0> a.concat([8] * 3)
=> [1, 2, 3, 4, 5, 6, 6, 8, 8, 8]
You can just use a range for this
(0..5).each{|i| array << 6}
array - stores a collection of variables
x - the number of times you want to push a number
n - the number you are pushing to the array
def push(array, x, n)
x.times{array.push(n)}
return array
end
you can do this instead. much cleaner to read and understand
arr.concat([3]*4)
So
[1,2]
will become
[1,2,3,3,3,3]