tags:

views:

157

answers:

5

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[10] = 2
array # => [1, 2, 3, nil, nil, nil, nil, nil, nil, nil, 2]

If not possible when assigning, how would I do it the best way afterwards? I thought of array.map { |e| e.nil? ? 0 : e }, but well…

Thanks!

+1  A: 

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}
Magnar
A: 

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}
gnibbler
+2  A: 

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]
Ron DeVera
A: 

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]
glenn mcdonald
A: 

Hi, I am looking for the same mechanism when the Array contains empty values. I've tried this whithout success : @description.map {|e| e.empty? ? e : @leftover.choice} Whith this code the "" row are intact and all the others values are replaced.

SilverRuby