From: Wilson Bilkovich Date: 2006-01-12T23:51:54+09:00 Subject: Re: safe array index ? On 1/11/06, Edward Faulkner wrote: > On Thu, Jan 12, 2006 at 02:40:40AM +0900, Christer Nilsson wrote: > > Is it possible to catch index out of range ? > > I managed to redefine Array, but I want to have both possibilities. > > You can use a delegator: > > require 'delegate' > > class SafeArray < DelegateClass(Array) > def [](index) > raise "index error" if index.abs >= size > super(index) > end > end > I've been trying to get my head around Delegator, but I'm not seeing what it does here. Subclassing Array seems to work the same way. irb session: irb(main):001:0> class SafeArray < Array irb(main):002:1> def [](index) irb(main):003:2> raise "Index error" if index.abs >= size irb(main):004:2> super(index) irb(main):005:2> end irb(main):006:1> end => nil irb(main):007:0> a = SafeArray.new => [] irb(main):008:0> a.concat [1,2,3,4,5] => [1, 2, 3, 4, 5] irb(main):009:0> b = Array.new => [] irb(main):010:0> b.concat [1,2,3,4,5] => [1, 2, 3, 4, 5] irb(main):011:0> a => [1, 2, 3, 4, 5] irb(main):012:0> b => [1, 2, 3, 4, 5] irb(main):013:0> a[9] RuntimeError: Index error from (irb):3:in `[]' from (irb):13 irb(main):014:0> b[9] => nil