Reputation: 1
I've got the following text file.
bob jones,19,moore reef,yes,no
jenny smith, 21,reef park,yes,yes
any body, 12,somewhere,no,no
I would like each line to be in a separate array OR I would like separate arrays for each piece of data (eg. name_array, age_array, destination_array, etc).
How can I do either way?
Upvotes: 0
Views: 425
Reputation: 1
I did it this was;
f1 = File.open(filename,"r")
f1.each do | line|
i += 1
data = line.split(',')
#store data into arrays
passenger_name[i] = data[0] #passenger's name
passenger_age[i] = data[1]
passenger_destination[i] = data[2]
passenger_meal[i] = data[3]
passenger_dive[i] = data[4]
end
It stores each of the names, ages, destinations, etc in a different array which solves my problem better. Thanks for all your repsonses.
Upvotes: 0
Reputation: 434985
Load it with the CSV parser from the standard library:
require 'csv'
a = CSV.open('x.csv').map { |r| r.map(&:strip) }
The will give you an a
like this:
[
[ "bob jones", "19", "moore reef", "yes", "no" ],
[ "jenny smith", "21", "reef park", "yes", "yes" ],
[ "any body", "12", "somewhere", "no", "no" ]
]
Then you can use b = a.transpose
to flip the rows and columns to get this in b
:
[
[ "bob jones", "jenny smith", "any body" ],
[ "19", "21", "12" ],
[ "moore reef", "reef park", "somewhere" ],
[ "yes", "yes", "no" ],
[ "no", "yes", "no" ]
]
And then from there you can pull out the individual arrays if you want them:
names, ages, destinations, flags1, flags2 = *b
I had to guess the flags1
and flags2
names.
Upvotes: 5
Reputation: 88478
Split the file into lines with readlines
then for each line use String#split
over the comma. Then, if you like (for your "second way") transpose.
Given the file people.txt
bob jones,19,moore reef,yes,no
jenny smith, 21,reef park,yes,yes
any body, 12,somewhere,no,no
Then lines of the file are obatined like this:
people = IO.readlines("people.txt")
p people
This gives
["bob jones,19,moore reef,yes,no\n",
"jenny smith, 21,reef park,yes,yes\n",
"any body, 12,somewhere,no,no"]
At this point you have some extra newlines in there, but they go away when you process line by line, adding String#chomp
:
result = []
people = IO.readlines("people.txt")
people.each {|line| result << line.chomp.split(",")}
p result
This gives
[["bob jones", "19", "moore reef", "yes", "no"],
["jenny smith", " 21", "reef park", "yes", "yes"],
["any body", " 12", "somewhere", "no", "no"]]
The second part of your question is how to get slices per column. The easiest way here is to use transpose
. Like so:
result = []
people = IO.readlines("people.txt")
people.each {|line| result << line.chomp.split(",")}
p result.transpose
This gives
[["bob jones", "jenny smith", "any body"],
["19", " 21", " 12"],
["moore reef", "reef park", "somewhere"],
["yes", "yes", "no"],
["no", "yes", "no"]]
UPDATE I had to edit my answer to add in the chomps! Also FYI you may want to add in some string trimming, too. I'll let you look that one up. :-)
Upvotes: 1