Spreading nil Into a Ruby Array
Spreading nil
into an array doesn't add an entry into a Ruby array:
[*nil] # => []
a = [1, 2, 3]
[*nil, *a] # => [1, 2, 3]
One might expect this to insert nil in the array, but this isn't the case. This feature could be useful when passing dynamically assigned, nullable items into an array.
def foo(arg)
[*arg]
end
nullable_var = params[:foo]
foo(nullable_var).each { |x| act_on(x) } # => [] if nullable_var is nil
Tweet