Posted by Anonymous on Tue 23rd Oct 16:44 (modification of post by view diff)
View followups from Anonymous | download | new post
- class File
- # This method could be implemented in two lines, but I'll spread it out so you can understand.
- def File.to_matrix(filename)
- file_data = File.read(filename) # First, we read the file in.
- rows = file_data.split("\n") # Split all the lines up into rows.
- # collect is a method on an array that takes a block (which is like an inline function).
- # It calls this block once for each element of the array and then returns an array of
- # all the results.
- rows.collect do |row|
- columns = row.split(" ") # Splits each row's string into columns (separated by spaces)
- columns.collect{ |column| column.to_f } # Convert each column from a string to a floating point value.
- # Those columns, now converted into numbers, are returned.
- end
- # Now we're returning an array of arrays like [row][column].
- end
- end
- my_matrix = File.to_matrix("my_data.txt")
- puts my_matrix.inspect # Writes out the matrix in legible form.
- my_matrix[2][3] # Returns the value in the 2nd row and the 3rd column.
Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.