Connecting Tech Pros Worldwide Help | Site Map

Reading variables in a file

Newbie
 
Join Date: Oct 2006
Posts: 1
#1: Oct 27 '06
I'm thinking of migrating from Fortran to Ruby. Do you think i should go ahead??
First problem i have.
How to read a file with several fields? This means:
Imagine a file:
Peter4 1990
Sam 3 1980
Grac6 1991

I would like to read for each line:name, order and year (3 variables per line). How can i do this? and how can i write them into a file??
Thank you in advance.
Newbie
 
Join Date: Nov 2006
Posts: 2
#2: Nov 14 '06

re: Reading variables in a file


Quote:

Originally Posted by ogrecio

I'm thinking of migrating from Fortran to Ruby. Do you think i should go ahead??
First problem i have.
How to read a file with several fields? This means:
Imagine a file:
Peter4 1990
Sam 3 1980
Grac6 1991

I would like to read for each line:name, order and year (3 variables per line). How can i do this? and how can i write them into a file??
Thank you in advance.

Well if you are programming in Fortran you will have to first learn about object oriented programming because unless Fortran as evolve since I programmed in it (in the days of punch cards) you will have a culture shock if you try this with no OOP training.

One way to solve your problem in Ruby would start with something like (hold on to your seat!):

File.open("D:\\TEMP\\DATA.TXT").each() do |line|
stringArray = line.split()
puts "Name = #{stringArray[0]} and Year = #{stringArray[1]}"
# Add your code here (remove the puts above)
end


So assuming your data is in a text file D:\\TEMP\\DATA.TXT the code above would output:

Name = Peter4 and Year = 1990
Name = Sam and Year = 3
Name = Grac6 and Year = 1991


Now you can see that on line 2 the year for Sam is wrong. THis is because on the second line the data in your post contained a blank between Sam and 3.
Removing this typo you would get:

Name = Peter4 and Year = 1990
Name = Sam3 and Year = 1980
Name = Grac6 and Year = 1991


Of course you could add error checking for the data.

Get a copy of "Programming Ruby" by Dave Thomas and good luck.

JS
Reply