5

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

1
  • Array[] is not what you mean. [] is sufficient. Empty argument lists on methods are also omitted by convention, so it's simply initialize. Commented Jul 16, 2016 at 12:16

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Worth mentioning ; is only necessary for collapsing multiple lines together, sometimes that's handy for things like x.each { |y| y.do_thing; y.do_other }. They shouldn't be present unless you're doing that even though they are otherwise ignored.
True. That's exactly and only the case in which I use ; in ruby.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.