Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read a text file into an array of array (each sub-array being a row in the text file?)

so I'm pretty much a n00b at Ruby, and I've put together a code to solve a MinCut problem (for an assignment, yes - that part of the code I've put together and tested), and I can't figure out how to read a file and put it into an array of arrays. I have a text file to read, with columns of varying length as below

1 37 79 164

2 123 134

3 48 123 134 109

and I'd like to read it into a 2D array, where each line and columnn is split, with each line going into one array. So the resulting array for the above example would be :

[[1, 37, 79, 164], [2, 123, 134], [3, 48, 123, 134, 109]]

My code to read the text file is below:

def read_array(file, count)
  int_array = []
  File.foreach(file) do |f|
    counter = 0
    while (l = f.gets and counter < count ) do
      temp_array = []
      temp_array << l.to_i.split(" ")
      int_array << temp_array
      counter = counter + 1
    end

  end
  return int_array
end

Any help is greatly appreciated!

Also, if it helps, the error I'm currently getting is "block in read_array': private method 'gets' called for # "

I've tried a few things, and have gotten different error messages though...

like image 695
Howzlife17 Avatar asked Jul 26 '13 14:07

Howzlife17


People also ask

How do I read a text file into an array?

Use the fs. readFileSync() method to read a text file into an array in JavaScript, e.g. const contents = readFileSync(filename, 'utf-8'). split('\n') . The method will return the contents of the file, which we can split on each newline character to get an array of strings.

How do you read a text file and store it to an array in Java?

In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method.

How do I convert a text file to an array in C++?

Insert data from text file into an array in C++ Firstly we start from header file in which we used three header file(iostream,fstream,string) iostream is used for input output stream and fstream is used for both input and output operations and use to create files, string is used for Saving The Line Into The Array.


1 Answers

File.readlines('test.txt').map do |line|
  line.split.map(&:to_i)
end

Explanation

readlines reads the whole file and splits it by newlines. It looks like this:

["1 37 79 164\n", "2 123 134\n", "3 48 123 134 109"]

Now we iterate over the lines (using map) and split each line into its number parts (split)

[["1", "37", "79", "164"], ["2", "123", "134"], ["3", "48", "123", "134", "109"]]

The items are still strings, so the inner map converts them to integers (to_i).

[[1, 37, 79, 164], [2, 123, 134], [3, 48, 123, 134, 109]]
like image 154
tessi Avatar answered Nov 15 '22 12:11

tessi