Assign an array and replace the resulting nil values

Hello!

When assigning a value to an array, as in the following, how can I replace nilwith 0?

array = [1,2,3]
array[10] = 2
array # => [1, 2, 3, nil, nil, nil, nil, nil, nil, nil, 2]

If this is not possible with the appointment, how will I do it best after that? I thought about array.map { |e| e.nil? ? 0 : e }, but well ...

Thank!

+5
source share
6 answers

There is no built-in function to replace nilin an array, so yes, that mapis the way to go. If a shorter version makes you happier, you can do:

array.map {|e| e ? e : 0}
+5
source

To change an array after assignment:

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

Please note that this also converts falseto 0.

, :

i = 10
a = [1, 2, 3]
a += ([0] * (i - a.size)) << 2
# => [1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 2]
+12

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

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

array.map!{|x|x.nil? ? 0:x}
+1
source
a.select { |i| i }

This answer is too short, so I add a few more words.

+1
source

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

array.map!(&:to_i)
+1
source

Another approach would be to define your own function to add the 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
source

All Articles