From: "juan pedro meriƱo" Date: 2007-06-29T22:57:12+09:00 Subject: Re: newbie questions on processing numerical data from text files ------=_Part_71802_18767274.1183125432679 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: quoted-printable Content-Disposition: inline How i create array under ruby? for example need create a vector type array 2007/6/29, Axel Etzold : > > Dear Baptiste, > > welcome to Ruby! > > > Here is my practical problem: > > > > - I open a text file, > > (... which already exists): > > interesting_text=3DIO.readlines(file_name) > > gives you an Array, with the lines as entries > > > > >locate a line according to some keyword > > > interesting_text.delete_if{|line| /(r|R)uby/.match=3D=3Dnil} > > removes all lines that don't contain the string Ruby or ruby, > > > or line number, > > > interesting_text[line_number] # (start counting at 0) > > > > > and change a value > old_value=3D1.2 > new_value=3D2.4 > > interesting_text.sub!(value.to_s,new_value.to_s) > > > - I run a fortran program > > result=3D`...` where ... is the system command you use to start > your fortran program, > > > > - I read a text file (output of this program), extract several > > numerical values > > You can do the reading with IO.readlines, the extraction with a > Regexp, > > > and export them in a two column text file > > and this via > > f=3DFile.new("my_result_file.txt","w") > f.puts formatted_text > f.close > > > > Here is the content of "sampleTextFile.dat": > > > > > this is a meaningless line > > > another one > > > > > > maybe this line acts as a keyword for the following data > > > > > I don't know how to interpret the values in brackets in the > following line: > > > > 1 3.1 (415, 19e-12) > > If you read the file in via IO.readlines, it's a String element > of an Array, say line=3D"1 3.1 (415, 19e-12)" > so you could do: > > numbers=3Dline.gsub(/[\(,\)]/,'').split <=3D removes brackets an gives > a four element Array (of Strings), which you can turn ito numbers via > eval > > number_array=3Dline.gsub(/[\(,\)]/,'').split.map{|x| eval(x)} > > Some other approach might be to assign variable names to each element > in a line > > vars_names=3D['a','b','c','d'] > array_of_hashes=3D[] > lines.each{|line| > vals_line=3Dline.gsub(/[\(,\)]/,'').split.map{|x| eval(x)} > tmp=3D{} > vars_names.each_with_index{|var_name,index| > tmp.store(var_name,vals_line[index]) > } > array_of_hashes< } > > will give something like: > > [{"a"=3D>1,"b"=3D>3.1,"c"=3D>415,"d"=3D>19e-12},...] > > > > Best regards, > > Axel > -- > Ist Ihr Browser Vista-kompatibel? Jetzt die neuesten > Browser-Versionen downloaden: http://www.gmx.net/de/go/browser > > --=20 Juan Pedro Meri=F1o Diaz Ing de Sistema CURN ------=_Part_71802_18767274.1183125432679--