Assign to an array and replace emerged nil values

Posted by Tobias on Stack Overflow See other posts from Stack Overflow or by Tobias
Published on 2010-03-27T01:12:55Z Indexed on 2010/03/27 1:23 UTC
Read the original article Hit count: 390

Filed under:
|
|

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!

© Stack Overflow or respective owner

Related posts about ruby

Related posts about arrays