From: RichardOnRails Date: 2008-05-05T05:40:02+09:00 Subject: Re: Matrix-element extractor -- How to define it On May 3, 9:06 pm, Daniel Finnie wrote: > Hi, > > You do this: > class Array > alias old_[] [] > def [] *args > if *args.length == 2 && args[0].is_a? Integer && args[1].is_a? Integer > get(*args) > else > old_[](*args) > end > end > > Of course, this would remove some of the functionality of an Array for > every Array, not just matricies. Consider making a subclass of Array > like this: > class Matrix < Array > ... > end > > Now you can modify Matrix at will without affecting Array. > > If you are creating a Matrix for purely pragmatic reasons (i.e., not > as an excercise) then there is an excellent Matrix class in the Ruby > standard library:http://ruby-doc.org/stdlib/ > > Dan > > On Sat, May 3, 2008 at 4:05 PM, RichardOnRails > > wrote: > > Hi, > > > I defined and populated a 9x9 matrix (Array of Arrays) of strings, m > > > I defined an element-extractor: > > > class Array > > def get(i,j) > > line =self[i-1] > > char = line[j-1] > > end > > end > > > To get the first element of the second row, I used the following, > > which worked fine: > > > m.get(2,1) > > > I'd like to write merely m(2,1). How can I do that simply? > > > Thanks in Advance, > > Richard Hi Daniel, Thanks for the "kick start" and the Matrix class. I got the latter working, but I'm going to "roll my own" because I want a Sudoku solver that works the way I do manually. I know there's a free solver written in VisualProlog, but like Frank Sinatra, "I'll do it my way" :-) > alias old_[] [] I'm running ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-mswin32]. It barfed on "old_", so I substituted: else super(*args) which worked fine. Best wishes, Richard