0

So far I've loaded an entire file into an array (1 line per array element). Then I've learned how to search for the correct lines needed. Now I need to split those lines so I can use the data.

1 array element (1 line from file): data,data,data,data,data

The first data column is text, the others are numbers. How do I from here split this data into something so I can do math on just one of these columns or plus 2 together, ect ?

As just a secondary note. I have a file with thousands of lines. But I'm picking 20 elements at a time. So I need to do this for 20 elements that are next to each other. So array[56],57,58, ect.

So I can then do math on row 1 column2 - row 3 column 4. Ect. (if this were set up in excel it would be like this - but you get the point - but it can be set up in any way as long as I can know how to get to individual data)

Thanks in advance.

1
  • So as an example of how I try to troubleshoot this. I do find things like split. But then what do I do with it. I've been able to split data but how do I name the data something so I can point to it? And what kind of data structure would I use? Just stuff like this I'm still learning thats why I'm asking a kinda noob question. I just started programming. Hopefully I'll be soon able to do most simple things inefficiently and then learn later how to do them better. Isn't that how it works? :) Commented Aug 14, 2012 at 13:30

2 Answers 2

1

You can just use String::split.

"1,2,3,4,a,b,c,d".split(',')         #=> ["1", "2", "3", "4", "a", "b", "c", "d"]

You can then convert the array elements to integers or floats as needed, as in

str = "1,2,3,4,a,b,c,d"
arr = str.split(",")

i = arr[0].to_i
f = arr[1].to_f

Additionally, if you are working with CSV files, you might consider using Ruby's CSV library.

Sign up to request clarification or add additional context in comments.

2 Comments

yeah but my starting data looks like this: array[57] - so I would do array[57].split(',') ? And then what? Thanks for the answer btw.
Assuming that array[57] is a string containing a line from your file, then yes, you can call array[57].split(',').
1

The file structure you've described is similar to csv files. To parse csv file in ruby, you can use the surprise... CSV library which is part of std library of ruby.

require 'CSV'
data = CSV.read(path_to_your_csv_file)

Now, you have your data loaded. To iterate over large blocks each time you can use each_cons

data.each_cons(20) do |rows| 
  #do something
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.