From: Daniel Martin Date: 2006-08-16T20:44:52+09:00 Subject: Re: [QUIZ] Newbie doubts about the quiz "Kroeger, Simon (ext)" writes: > You know I like NArray, but perhaps there is an even > cooler way this time :) > > ----------------------------------------------- > my_array = [1, 2, 3] > another_one = [1, 2, 3] > > p my_array[-1] #=> 3 grmpf... > p another_one[-1] #=> 3 yeah, what else? > > class << my_array > def [] index > return nil if index < 0 > super > end > end > > p my_array[-1] #=> nil, hehe, nice! > p another_one[-1] #=> 3 woot, woot > ----------------------------------------------- > > I don't know if this is really the right way, but the > OP was asking for a super-cool Ruby-esque way, right? Well, yeah, but in the context of the problem what you need is a two-dimensional array: n = (ARGV.first||'6').to_i my_array = Array.new(n) { inner = Array.new(n) {0} class << inner def [] index return nil if index < 0 super end end inner } class << my_array def [] index return [] if index < 0 ret = super return [] if ret == nil ret end end I could compress three lines there into "super or []", but I don't know if the OP wants to maybe use "true" and "false" as values in his array. Once you do this, you properly get nil for all of: my_array[0][-1] my_array[-1][0] my_array[n][0] my_array[0][n] Now, can someone build this into a generic n-dim array class without using all these singleton classes?