Ininter Ininter - 12 days ago 5
Ruby Question

Recognizing an array of constructor

What can I do to recognize an array which is declared in a constructor, by method, in this class?

I received an error:


undefined local variable or method 'myArray'


class Calc
def initialize()
myArray = []
end

def add4ToArray()
myArray.push(4)
puts myArray.size
end
end

obj1 = Calc.new
obj1.add4ToArray()

Answer

You need to declare it as an instance variable as opposed to a local variable. In the constructor, use @myarray = [].

Comments