If else
-
a = [] counter = 0 file = File.new("trial.txt", "r") while (line = file.gets) a[counter] = line if counter % 4 == 0 # lines 0 , 4, 8 etc machine = "#{a[counter]}" elsif counter % 4 == 0.25 # lines 1, 5, 9 etc x = a[counter].to_f elsif counter % 4 == 0.5 # lines 2, 6, 10 etc y = a[counter].to_f elsif counter % 4 == 0.75 # lines 3, 7, 11 etc rot = a[counter].to_i end end
-
This should work:
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 machine = "#{a[counter]}" 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 end end
-
You haven't understood what I said several posts back
elsif counter % 4 == 0.25 # lines 1, 5, 9 etc
will never return true as it returns '1' NOT '0.25'... to test this simply type 1%4 or 5%4 in the Ruby Console and you'll get '1' NOT '0.25' !
Also note how 1/4 will return 0 because dividing an integer by an integer gives an integer [and 5/4 gives 1 !]... BUT 1/4.0 gives 0.25 as you have divided an integer by a float and you get a float.
SO your test iselsif counter % 4 == 1 # lines 1, 5, 9 etc
-
hmmm this worked now...but I didn't understand why you did 1% 4 = 1.0 etc?
-
You may wish to use the 3rd line as:
file = IO.readlines("trial.txt")
.. then change the
while
loop to an arrayeach
iterator:
` file.each_with_index do |line,counter|code
end`
-
@borg.stef said:
hmmm this worked now...but I didn't understand why you did 1% 4 = 1.0 etc?
Because I did what TIG said, I tested it at the console, and saw it returned 1,2,3, ...
-
ok sorry TIG i saw your post now
-
@dan rathbun said:
You may wish to use the 3rd line as:
file = IO.readlines("trial.txt")
.. then change the
while
loop to an arrayeach
iterator:
` file.each_with_index do |line,counter|code
end`
If you do this, you do not need
a = []
, because the varfile
is the array (IO.readlines
returns an array of textlines.) -
ok thanks both!!
-
From the looks of your code you're interested specifically in blocks of four lines, in which case you may gain some mileage out of the array.slice method by doing the following.
for i in 0..a.length/4 #there are i blocks of four lines machine,x,y,rot = a.slice(i*4,4) #more code end
Advertisement