Is there a preferred and type-safe way without forced typecast to remove nils from Array?
[1, nil].select{|x| !!x}
// => Array(Int32 | Nil)
Something like special select
?
P.S.
The use case when I hit this issue - I want to calculate median
and the sort
won't work:
[1, nil].select{|x| !!x}.sort
Map with zeros [1, nil].map{|x| x || 0}
won't work as unlike let's say sum
for some operations the length does matter (median
for example).
Array#compact
will remove nils from the Array:
[1, nil].compact # => [1] (Array(Int32))