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]

      

+3


source to share


5 answers


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]

. Now a.size

will give you 3

where the last index is 2

. So, when you use a.size

with #fill

, then you are talking to start pushing the object out 3

several n

times.

+8


source


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]

      

+2


source


You can just use a range for this

(0..5).each{|i| array << 6}

      

0


source


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

      

0


source


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]

0


source







All Articles