Stupid Ruby Tricks: Arrays

July 24, 2019

[ruby]

If you want a Ruby array with "hard" boundaries, use Array#fetch instead of Array#[]

irb: x = [1,2,3]
===> [1, 2, 3]
irb: x.fetch(3)
IndexError: index 3 outside of array bounds: -3...3

However: If you want to prohibit negative indexes (which usually refer to offsets from the end of the Array), you can build this simple override:

irb: x.define_singleton_method :fetch do |index|
     if index.negative?
       fail IndexError, "index #{index} outside of array bound: 0...#{length}"
     else
       super(index)
     end
   end
===> :fetch
irb: x.fetch(0)
===> 1
irb: x.fetch(-1)
IndexError: index -1 outside of array bound: 0...3
Stupid Ruby Tricks: Arrays - July 24, 2019 - Ken Mayer