From: Axel Etzold Date: 2007-06-29T22:32:18+09:00 Subject: Re: newbie questions on processing numerical data from text files Dear Baptiste, welcome to Ruby! > Here is my practical problem: > > - I open a text file, (... which already exists): interesting_text=IO.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==nil} 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=1.2 new_value=2.4 interesting_text.sub!(value.to_s,new_value.to_s) > - I run a fortran program result=`...` 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=File.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="1 3.1 (415, 19e-12)" so you could do: numbers=line.gsub(/[\(,\)]/,'').split <= removes brackets an gives a four element Array (of Strings), which you can turn ito numbers via eval number_array=line.gsub(/[\(,\)]/,'').split.map{|x| eval(x)} Some other approach might be to assign variable names to each element in a line vars_names=['a','b','c','d'] array_of_hashes=[] lines.each{|line| vals_line=line.gsub(/[\(,\)]/,'').split.map{|x| eval(x)} tmp={} vars_names.each_with_index{|var_name,index| tmp.store(var_name,vals_line[index]) } array_of_hashes<1,"b"=>3.1,"c"=>415,"d"=>19e-12},...] Best regards, Axel -- Ist Ihr Browser Vista-kompatibel? Jetzt die neuesten Browser-Versionen downloaden: http://www.gmx.net/de/go/browser