I would like to extend an Ruby Array object, to make it returns Array.new if it's nil.
My solution:
Overwrite []
and at
.
module NullSafeArray
def at(index)
value = super
return Array.new if value.nil?
value
end
def [](index)
value = super
return Array.new if value.nil?
value
end
end
The problem:
This works:
assert_equal Array.new [].to_be_null_safe[3]
But this will fail:
a, b = [nil, 2].to_be_null_safe
assert_equal Array.new, a
Which method else should be overwritten to do this?
Update:
Your answer should passes this:
a, b = [9].to_null_safe
assert a == 9
assert b == Array.new
It could be a, b, c, d =
. You don't know how many comma there is.
I guess you know what method to overwrite by looking about Ruby's source code, I tried, but it's kind of hard to find it.