Assign to an array and replace emerged nil values

后端 未结 6 1023
佛祖请我去吃肉
佛祖请我去吃肉 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:35

    To change the array in place

    array.map!{|x|x ?x:0}
    

    If the array can contain false you'll need to use this instead

    array.map!{|x|x.nil? ? 0:x}
    

提交回复
热议问题