Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign to an array and replace emerged nil values

Tags:

arrays

null

ruby

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!

like image 575
Tobias Avatar asked Mar 27 '10 01:03

Tobias


People also ask

How do you remove nil from an array?

Array#compact () : compact () is a Array class method which returns the array after removing all the 'nil' value elements (if any) from the array. Syntax: Array. compact() Parameter: Array to remove the 'nil' value from. Return: removes all the nil values from the array.

Is an empty array nil?

It has a length and capacity of 0 with no underlying array, and it's zero value is nil .


2 Answers

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]
like image 128
Ron DeVera Avatar answered Sep 28 '22 07:09

Ron DeVera


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}
like image 25
Magnar Avatar answered Sep 28 '22 05:09

Magnar