Assign to an array and replace emerged nil values

后端 未结 6 1025
佛祖请我去吃肉
佛祖请我去吃肉 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:20
    a.select { |i| i }
    

    This answer is too short so I am adding a few more words.

    0 讨论(0)
  • 2021-01-17 19:21

    To change the array after assignment:

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

    Note that this also converts false to 0.

    If you want to use zeros during assignment, it's a little messy:

    i = 10
    a = [1, 2, 3]
    a += ([0] * (i - a.size)) << 2
    # => [1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 2]
    
    0 讨论(0)
  • 2021-01-17 19:21

    nil.to_i is 0, if all the numbers are integers then below should work. I think It is also the shortest answer here.

    array.map!(&:to_i)
    
    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 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}
    
    0 讨论(0)
  • There is no built-in function to replace nil in an array, so yes, map is the way to go. If a shorter version would make you happier, you could do:

    array.map {|e| e ? e : 0}
    
    0 讨论(0)
提交回复
热议问题