cbutler cbutler - 4 months ago 21
Ruby Question

Ruby - read each line in file to object and add object to array

I am very new to Ruby and trying to read each line of a file. I want to create an object called LineAnalyzer using each line and then add that object to an array called analyzers.

The code I am trying is

Class Solution
attr_reader :analyzers;

def initialize()
@analyzers = Array[];
end

def analyze_file()
count = 0;

f = File.open('test.txt')

#* Create an array of LineAnalyzers for each line in the file

f.each_line { |line| la = LineAnalyzer.new(line, count) }
@analyzers.push la;
count += 1;
end
end
end


Any help or suggestions would be greatly appreciate!!

Answer

If I have understood you correctly, this should work:

class Solution 
    attr_reader :analyzers

    def initialize()
      @analyzers = []
    end

    def analyze_file()
      count = 0;
      File.open('test.txt').each_line do |line| 
          la = LineAnalyzer.new(line, count) 
          @analyzers.push la
          count += 1
      end
    end
end

Little digressing from question, please note that - at most places in ruby you don't need ;. Ruby is good so it doesn't complain about it, but its good to stay with the standard conventions.

Comment in case of any problem.

Hope it helps :)