Getting info from a text file
-
This is my code where im getting information from a text file. it is a loop like this: 0th line in variable machine (string), 1nd line in variable x (integer), 2rd line in variable y (integer), 3th line in var rot (integer), 4th line in machine again etc. however if in the string line there is "floor" written, those 4 lines will be skipped and go to the next string line (therefore counter = counter +4). However when i run it, nothing happens
a = [] counter = 0 file = File.new("trial.txt", "r") while (line = file.gets) a[counter] = line if counter % 4 == 0.0 # lines 0 , 4, 8 etc if a[counter] = #{floor} counter = counter + 4 else machine = "#{a[counter].3ds" end elsif counter % 4 == 1.0 # lines 1 , 5, 9 etc x = a[counter].to_f elsif counter % 4 == 2.0 # lines 2 , 6, 10 etc y = a[counter].to_f elsif counter % 4 == 3.0 # lines 3 , 7, 11 etc rot = a[counter].to_i
-
A much simpler way is to read all of the file's lines into an array like this
lines=IO.readlines(file_path)
then process the lines in turn...
lines.each{|line| ...### do something to 'line' or use 'next' if it's not a type you want... }
This way you don't need to open/close the file or use 'counters' etc... -
But if you still wish to use a counter, you may by using the each_with_index iterator (that is mixed into the Array class, from module Enumerable.)
lines.each_with_index {|line,counter| ...### do something to 'line' or use 'next' if it's not a type you want... }
-
The reason it does not work is this line:
if a[counter] = #{floor}
should be:
if a[counter] == "floor"
Because:
(1)=
is the assignment operator, and==
is the equality method for class String.(2) the
#{var}
replacement operator must be nested within a double-quoted String literal.
BUT... in your case, "floor" is NOT a variable (reference), it is a String value, so you just need to specify the literal String. -
By the way... if YOU are creating the files.. why not simplify things and write out CSV records, where each line is:
"string tag",x,y,rot
We have a topic on reading CSV text files:
[code] reading a CSV fileEDIT: Oh you are using MatLab written files, as in this post http://forums.sketchucation.com/viewtopic.php?f=180&t=35961&start=30#p319047
Advertisement