From: ES Date: 2005-05-11T01:35:07+09:00 Subject: Re: help with reading part of textfile into matrix rgilaard@few.vu.nl wrote: > Oof course I am confused a s a ruby newbie!! > > However, > I've made this out of your post: > matrix = [] > > DATA = File.new("testfile.txt", "r") > DATA.each do | line | > if /^((?:\s+(?:\d+))+)/ =~ line > matrix << $1.split.map{|value| value.to_i} > end > end > > p matrix > puts matrix[2,2] > DATA.close > > But this gives me as result > 707 > 293 > 441 > > while I would expect 441. > > What is going on? Here you would want 'puts matrix[2][2]'. Your form actually returns a slice, i.e. "starting from element 2, give me 2 elements" (and there is only one). > Brgds > Robert > > Quoting Brian Schr�der : > > >>On 10/05/05, rgilaard@few.vu.nl wrote: >> >>>Dear all, >>> >>>I am new to Ruby and I'm looking for a way to use Ruby (1.8) to read a part >> >>of >> >>>a textfile into a matrix. >>> >>>The textfile lokks like: >>> >>>=== Confusion Matrix === >>> >>> a b c <-- classified as >>> 7494 4044 100 | a = WEL >>> 2039 18691 11 | b = NIET >>> 707 293 441 | c = NOOIT >>> >>>So what i want is that this matrix is read into a matrix variable in a >> >>ruby >> >>>program which I can use then to manipulate in every way I want. >>> >>>Can someone help me with this? >>> >>>I figured out that I could maybe use a regexp /\s*a\s*/ to search for the >> >>line >> >>>with a b c >>>Then I skip that line and start to read the following line position by >> >>position >> >>>into the first row of the 3-by-3 matrix. >>> >>>How could this be done? >>> >>>Thanks in advance, >>>Robert Gilaard >>> >> >>Confused? ;-) >> >>$ cat confusion.rb >>matrix = [] >> >>DATA.each do | line | >> if /^((?:\s+(?:\d+))+)/ =~ line >> matrix << $1.split.map{|value| value.to_i} >> end >>end >> >>p matrix >> >>__END__ >> a b c <-- classified as >> 7494 4044 100 | a = WEL >> 2039 18691 11 | b = NIET >> 707 293 441 | c = NOOIT >> >>$ ruby confusion.rb >>[[7494, 4044, 100], [2039, 18691, 11], [707, 293, 441]] >> >>regards, >> >>Brian Schr�der >> >>-- >>http://ruby.brian-schroeder.de/ >> >>multilingual _non rails_ ruby based vocabulary trainer: >>http://www.vocabulaire.org/ | http://www.gloser.org/ | >>http://www.vokabeln.net/ >> E -- template void quack(duck& d) { d.quack(); }