I want to set the number of elements in the array to 5 and fill the missing elements with 0s from the end.
Is there a method that can be filled with 0s?

# For the time being, we have achieved the expected movement below.
(5 --array.length) .times do array<<0 end
  • Answer # 1

    It seems that there is no such thing as one method.

    array.concat ([0] * (5-array.length))

    (To avoid an error if the length is originally exceededmaxuse)

    There may be a simpler solution, digging into why you wanted to do that and thinking about how you could avoid it.

  • Answer # 2

    Array.new (5,0)There is also a method of making it with and overwriting it.

    If you get an error when calculating with another size 5 arrayarry [i] .to_iThere is also a way to do it.

  • Answer # 3

    array = array.push (* Array.new (5,0)). shift (5)