Home > Back-end >  How can i complete to fill the array?
How can i complete to fill the array?

Time:01-21

I want to complete to fill the array, for example i already have an array like this:

[1,2,3,4,5] and now over this i want to complete to fill the array until 10 with an value 9

i need this output

[1,2,3,4,5,9,9,9,9,9]

i was trying with a loop

but i dont know if there are another best way to do this

CodePudding user response:

Array.new can create an array with a default value and size.

So, if you know that the resulting length should be 10 and the value to fill the missing elements is 9, you can calculate how many elements you need from the difference between 10 and the length of elements in [1,2,3,4,5], and create a new array from both arrays using Array# :

arr   Array.new(10 - arr.size, 9)
# [1, 2, 3, 4, 5, 9, 9, 9, 9, 9]

CodePudding user response:

If you want to fill the array to a specific length with a specific value, you can use the aptly named Array#fill method:

a = [1,2,3,4,5]

a.fill(9, a.length..9)
#=>  [1, 2, 3, 4, 5, 9, 9, 9, 9, 9]
  •  Tags:  
  • Related