-1

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

Y Rao
  • 43
  • 3
  • 1
    It is not clear what you want to do. Do you want to define attributes on the array class? Or, do you want to define attributes that are array on some other class? Or anything else? – sawa Nov 02 '17 at 05:15
  • I have updated my post. The requirement is to declare an array object, update it with entries, then print it outside the class. – Y Rao Nov 02 '17 at 09:39
  • I think you've misunderstood what `attr_accessor` (note the spelling) is used for. It's a convention for accessing/updating instance variables that are usually defined upon initialization. Hint: you have no instance variables defined anywhere. – Sagar Pandya Nov 02 '17 at 13:53

1 Answers1

4

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

class MyClass
  attr_accessor :my_array
end
Dennis Vennink
  • 1,083
  • 1
  • 7
  • 23