How to use 'attr_accessor' in ruby for an array object

947 Views Asked by At

How can I use attr_accessor for an array object? Is this valid?

attr_accessor :my_arrayobject[]

This question explains attr_accessor uses, but does not tell how to use it for arrays.

Declaring the array as

class Abc
  arr_accessor :my_arrayobject

  def initialize
      self.my_arrayojbect = []
  end
  ....
  def update
     self.my_arrayobject << parameter
  end
end

p1 = Abc.new
puts p1.my_arrayobject

When I am doing this, the array is getting overwritten everytime I am updating it.

The idea is to declare an array object, update it with entries, then print it outside the class

1

There are 1 best solutions below

0
Dennis Vennink On

It is exactly the same as any other type. Ruby is a dynamic language.

class MyClass
  attr_accessor :my_array
end