From: Chris Gernon Date: 2006-10-27T23:00:53+09:00 Subject: Re: reading variables in a file Ooo Grec wrote: > I'm thinking of migrating from Fortran to Ruby. Do you think i should go ahead?? That entirely depends on what the application is, if you currently use a number of Fortran libraries, etc. However, I say it never hurts to learn another language (gives you another tool in your tool belt), and Ruby is one of the easiest to learn and most useful out there. > First problem i have. > How to read a file with several fields? This means: > Imagine a file: > Peter4 1990 > Sam 3 1980 > Grac6 1991 A typical Ruby program to do this would look something like this. This is pretty simple, so I combined reading from the file and writing to a new file into the same program. Also, the real "Ruby Way" to do this would be to create a Person class with name, order, and year attributes ... but I figured a "quick and dirty" approach of storing the values in a hash would work for a simple example like this. (Note that # starts comments, except inside double quotes, where #{} inserts a variable or expression inside the double-quoted string). Hope this helps! #!/usr/bin/env ruby -w INPUT_FILE = 'data.txt' OUTPUT_FILE = 'new_data.txt' people = [] #empty array File.open(INPUT_FILE) do |data| # open file for reading data.each do |line| # for each line ... # if line matches (text containing no digits, then 1 or more digits, then a space, then 4 digits) if line =~ /^(\D*)(\d+) (\d\d\d\d)$/ person = {:name => $1.strip, :order => $2, :year => $3} # capture matched values in a hash people << person # add the person hash to the people array else puts "Read line that was not in expected format!" end end end puts "read #{INPUT_FILE} file" # puts: put string (print to stdout) puts 'Data read:' people.each do |person| # for each person hash in the people array ... puts "Name: #{person[:name]}, Order: #{person[:order]}, Year: #{person[:year]}" end File.open(OUTPUT_FILE, 'w') do |new_data| # open file for writing people.each do |person| # for each person hash in the people array ... new_data.puts "#{person[:name]} #{person[:order]} #{person[:year]}" # write string to file end end -- Posted via http://www.ruby-forum.com/.