Ruby - reading each line in the file for an object and adding the object to an array

I am very new to Ruby and trying to read every line of the file. I want to create an object called LineAnalyzer using each row, and then add this object to an array called parsers.

The code I'm trying to do 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 appreciated!

+4
source share
1 answer

If you understood 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

Distracting from the question, note that in most places in the ruby ​​you do not need ;. Ruby is good, so it does not complain about it, but it is useful to stay with standard conventions.

+3
source

Source: https://habr.com/ru/post/1648081/


All Articles