aneuch2
aneuch2

Reputation: 23

Ruby novice: Writing a method to read mulitple arrays from a file?

I have a file with ten separate columns of data separated by spaces. I have written the following code (and it works), but I feel that there is a much cleaner way to do what I am doing here:

#Generate ten separate arrays in which to store the columns
c0 = []; c1 = []; c2 = []; c3 = []; c4 = []; 
c5 = []; c6 = []; c7 = []; c8 = []; c9 = [];

#Append each item in each line to its own array
File.open(filename, 'r').each_line do |line|
  line = line.strip.split(' ')
  c0 << line[0]; c1 << line[1]; c2 << line[2]; c3 << line[3]; c4 << line[4]; 
  c5 << line[5]; c6 << line[6]; c7 << line[7]; c8 << line[8]; c9 << line[9]; 
end

I tried to write a method to accomplish this task, but I am essentially clueless on where to start. I imagine that there is a cleaner way to initialize n-number of arrays than how I have done...what is the 'ruby' way of doing that? Is it possible to do everything I am doing here in a single method that returns 10 arrays? Help/hints on how to accomplish this would be greatly appreciated.

Upvotes: 2

Views: 126

Answers (2)

seph
seph

Reputation: 6076

File.open(filename, 'r') do |infile|
  c = infile.lines.map(&:split).transpose
end

Now c is a two-dimensional array where each row is an array representing a column from the original file so c[0] = c0 and so on.

EDIT: This is probably a little dense. Some explanation:

infile.lines is an array where each element is a line from the file.

infile.lines.map(&:split) is short for infile.lines.map { |line| line.split }.

' ' is the default char to split on.

transpose turns the columns into rows.

Upvotes: 1

Maybe this piece of code helps:

   c = []
   File.open(filename, 'r').each_line do |line|
      line = line.strip.split(' ')
      columns = Hash.new
      index=0
      line.each do |column|
        columns[index] = column
        index+=1
      end 
      c.push(columns)
    end

Where each column is a Hash with an index by line part, and all lines are stored in a array

Upvotes: 2

Related Questions