Joachim
Joachim

Reputation: 3260

Changing an Object-encapsulated Array

Here is a minimal example of a data structure encapsulated by a class. The data structure should be accessible by class methods. Hence, I want to control the access for example to forbid certain modifications.

    class List
      attr_accessor :array

      def initialize
        @array = ["b"]
      end

      def addElement(v)
        @array.insert(v)
      end
    end


    a = List.new
    puts a.array.to_s
    a.addElement("a")
    puts a.array.to_s

The output is

["b"]
["b"]

The problem occured while using the graph theory gem plexus. The above is just a minimal example. I am trying to learn Ruby from a Java background.

Upvotes: 0

Views: 57

Answers (1)

Ajedi32
Ajedi32

Reputation: 48418

You're using Array#insert wrong. Consider using Array#<< or Array#push instead.

Upvotes: 1

Related Questions