I want to write a method for collection types, filter out all nil and cast down the type.
class Array(T)
def purge
self.compact.map(&.as(T))
end
end
a = [nil, 1, 2, nil] of Int32 | Nil
a = a.purge
p typeof(a[0])
After purge, Array(Int32 | nil) will be Array(Int32), but I don’t know how to make the code work.
Since T could be a compound type Int32 | nil, the code do nothing.
Note that you must use #compact (and not #compact!) and reassign the variable. This slight modification to the above code will not work:
a = [nil, 1, 2, nil] of Int32 | Nil
p typeof(a[0]) # => (Int32 | Nil)
p typeof(a) # => Array(Int32 | Nil)
a.compact! # <= THIS IS DIFFERENT
p typeof(a[0]) # => (Int32 | Nil)
p typeof(a) # => Array(Int32 | Nil)