Today I Learned

A Hashrocket project

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
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. Contact us and find out how we can help you.