cbutler
cbutler

Reputation: 933

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!!

Upvotes: 5

Views: 1328

Answers (1)

Harsh Trivedi
Harsh Trivedi

Reputation: 1624

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.

Upvotes: 4

Related Questions