jeudi 17 avril 2014

Ruby: Read a file into an associative array


Vote count:

0




I am learning Ruby coming from a C base background (C++, PHP, C#, ...)


I want to be able to read the file into an associative array where I can access the elements by the column head name.


My file is formatted as follows:



KeyName Val1Name Val2Name ... ValMName
Key1 Val1-1 Val2-1 ... ValM-1
Key2 Val1-2 Val2-2 ... ValM-2
Key3 Val1-3 Val2-3 ... ValM-3
.. .. .. .. ..
KeyN Val1-N Val2-N ... ValM-N

The only problem is I don't have a clue how to do it.

So far I have:



scores = File.read("scores.txt")
lines = scores.split("\n")
lines.each { |x|
y = x.to_s.split(' ')
}


... which gets close to what I want, but still am unable to get it into the format that is usable for me.


Thanks for pointing me in the right direction!


-Brianne



asked 17 secs ago






Aucun commentaire:

Enregistrer un commentaire