From: ara.t.howard@... Date: 2006-10-13T14:06:28+09:00 Subject: Re: Any way to get lists to throw exceptions on incorrect accesses? On Fri, 13 Oct 2006, Kenneth McDonald wrote: > Eero Saynatkari wrote: >> Since you asked.. :) >> >> We have managed to make do without Array access raising exceptions. >> >> I would REALLY recommend leaving behind the baggage of any previous >> languages and take a head-first plunge. In Ruby, Array access returns >> a nil if the index is not found. Embrace it! Form your code around the >> Ruby idioms, not the other way around! >> >> The payoff will be much greater. >> > Certainly possible. I'm not uncomfortable with new ways of doing things (I > really like Ruby iteration, for example), I'm just worried this difference > might cause hard-to-find errors. But I just posted that as a more general > question, so 'nuff said here :-) it's not that hard if you want, and you only need modify the array's you desire - not all of them in you program: harp:~ > cat a.rb class Array module BoundsCheck def [] a, *b b = b.shift max = case a when Numeric a when Range a.exclude_end? ? (a.end-1) : e.end else b end raise IndexError, max.to_s if max > (size - 1) super end end def bounds_check! extend BoundsCheck end end array = %w[ 0 1 2 ] 4.times{|i| puts "array[#{ i }] : #{ array[i].inspect }"} array.bounds_check! 4.times{|i| puts "array[#{ i }] : #{ array[i].inspect }"} harp:~ > ruby a.rb array[0] : "0" array[1] : "1" array[2] : "2" array[3] : nil array[0] : "0" array[1] : "1" array[2] : "2" a.rb:15:in `[]': 3 (IndexError) from a.rb:31 from a.rb:31 to be robust you'd want to wrap Array#slice and other 'index-y' methods. regards. -a -- my religion is very simple. my religion is kindness. -- the dalai lama