Question

How would I create an attr_accessor to array?

for example

class MyClass

  attr_accessor :my_attr_accessor

  def initialize()
  end

  def add_new_value(new_array)
    @my_attr_accessor += new_array
    return @my_attr_accessor
  end

end

my_class = MyClass.new
my_class.my_attr_accessor = 1
my_class.my_attr_accessor[1] = 2
my_class.my_attr_accessor.push = 3
my_class.add_new_value(5)

my_class.my_attr_accessor
=> [1, 2, 3, 5]
Was it helpful?

Solution

Just use an instance variable that points to an array and make an accessor from that instance variable.

Inside your class include something like this:

attr_accessor :my_attr_accessor
def initialize
    @my_attr_accessor = []
end

Note that usingattr_accessor will allow you to change the value of the variable. If you want to ensure that the array stays, use attr_reader in place of attr_accessor. You will still be able to access and set array elements and perform operations on the array but you won't be able to replace it with a new value and using += for concatenation will not work.

OTHER TIPS

If you are OK with the Array always existing, @david4dev's answer is good. If you only want the array to pop into existence on the first usage, and never want the user to be able to replace it with a new array (via assignment):

class MyClass
  def my_attr_accessor
    @my_attr_accessor ||= []
  end
  def add_new_value( value )
    my_attr_accessor << value
  end
  def add_new_values( values_array )
    my_attr_accessor.concat values_array
  end
end

The user could still call my_class.my_attr_accessor.replace( [] ) to wipe it out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top