From: Alex Gutteridge Date: 2007-12-06T09:53:41+09:00 Subject: Re: Capturing STDOUT from a system call (POSIX) into an array On 6 Dec 2007, at 09:38, Venks wrote: > Thanks for your quick reply. I realize that you don't even need to use > split. What I am missing is how to create a 2 dimensional array with > each line contents in an array assuming that they are separated by a > COMMA. > > Let me be more specific. Assume that we have a file under > /tmp/test.txt with the following contents. > > aaa, 10, test1 > bbb, 20, test2 > ccc, 30, test3 > ddd, 40, test4 > > I want to create a 2 dimensional array with each line being an array. > > lines = `cat /tmp/test.txt` will create a single dimensional array > by default. I'm not so sure about that last comment. As far as I know backticks always return a String. The easiest way to do what you want is just to split the String from backticks by line and then each line by whatever delimiter you chose. You can do this with map for instance: [alexg@powerbook]/Users/alexg/Desktop(47): cat test.txt aaa, 10, test1 bbb, 20, test2 ccc, 30, test3 ddd, 40, test4 [alexg@powerbook]/Users/alexg/Desktop(48): cat capture.rb p `cat #{ARGV[0]}`.split(/\n/).map{|line| line.split(/, /)} [alexg@powerbook]/Users/alexg/Desktop(49): ruby capture.rb test.txt [["aaa", "10", "test1"], ["bbb", "20", "test2"], ["ccc", "30", "test3"], ["ddd", "40", "test4"]] Alex Gutteridge Bioinformatics Center Kyoto University