tags:

views:

68

answers:

2

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.

+1  A: 

Simply extend Array class like this below

class Array
  def to_null_safe!
    each_with_index  do |variable, index|
      self[index] = "HELLO" if variable.nil?
    end
  end
end
Rishav Rastogi
I guess you should name your method `to_null_safe!`. Am I right?
floatless
yeah, correct. Thanks
Rishav Rastogi
A: 
class Array
  def to_be_null_safe
    map { |value| value.nil? ? "HELLO" : value }
  end
end

Also consider to use a custom object if you need to override lot of methods, instead of cluttering the Array space.

Simone Carletti
This will also convert `false` values.
Marc-André Lafortune
Right. I fixed the code.
Simone Carletti