1

can anyone tell me how to initialize an array of object in Ruby. I have my class Line:

class Line
  @@text
  @@number = 0
  @@file = 0
  @@paired

  def initialize(text, number, file = 0, paired = 1)
    @@text = text
    @@number = number
    @@file = file
    @@paired = paired
  end
end

And now i wish to initialize an Array of Lines, when i do parsedLines = Array.new() and in loop do parsedLines[i] = Line.new(line, number, file, 0) i got an array of Lines, but Array elements are initialize on last made Line object, how can i fix this, to have array of Line object?

1 Answer 1

2

That's what @@ does. It defines a class-level variable, shared by all instances of the class. Each time you declare a new instance, you're overwriting those values, so of course your entire array will appear to contain the same object.

Change @@ to @ in your initialize method, and remove the class-level @@ variables completely, they serve no purpose. You do not need to declare variables this way in Ruby.

The correct implementation would be:

class Line
  def initialize(text, number = 0, file = 0, paired = 1)
    @text = text
    @number = number
    @file = file
    @paired = paired
  end
end
Sign up to request clarification or add additional context in comments.

Comments

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.