Assign to an array and replace emerged nil values

后端 未结 6 1120
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-17 19:08

Greetings!

When assigning a value to an array as in the following, how could I replace the nils by 0?

array = [1,2,3]
array         


        
6条回答
  •  独厮守ぢ
    2021-01-17 19:25

    Another approach would be to define your own function for adding a value to the array.

    class Array
      def addpad(index,newval)
        concat(Array.new(index-size,0)) if index > size
        self[index] = newval
      end
    end
    
    a = [1,2,3]
    a.addpad(10,2)
    a => [1,2,3,0,0,0,0,0,0,0,2]
    

提交回复
热议问题