davej davej - 1 year ago 54
Ruby Question

Need to prohibit negative index values in array

I have an array

date_array
. If
i
is
0
, I'd like
date_array[i-1]
to return
nil
or an exception. I thought I could derive a subclass of Array for this, but I'm not sure where to go after that. Any ideas?

Answer Source

You could do this, but you shouldn't need to. You're going about this the wrong way, I feel, since the responsibility is yours, not Array's, to check the index value being passed.

Merely an example

def get_array_value (i)
  return data_array[i - 1] unless i < 0
  return nil
end

However, if you insist, this solution may work for you.

# arr = SpecialArray.new([1, 2, 3, 4, 5])

class SpecialArray < Array

  def [](i)
    return super(i) unless i < 0
    return nil
  end  

end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download