I was going through an online tutorial on Ruby module extends where the teacher explains the code with this
module Tracking def create(name) object = new(name) instances.push(object) # note this line return object end def instances @instances ||= [] end end class Customer extend Tracking attr_accessor :name def initialize(name) @name = name end def to_s "[#{@name}]" end end This was the output
puts "Customer.instances: %s" % Customer.instances.inspect puts "Customer.create: %s" % Customer.create("Jason") puts "Customer.create: %s" % Customer.create("Kenneth") puts "Customer.instances: %s" % Customer.instances.inspect Output: Customer.instances: [] Customer.create: [Jason] Customer.create: [Kenneth] Customer.instances: [#<Customer:0x007f2b23eabc08 @name="Jason">, #<Customer:0x007f2b23eabaf0 @name="Kenneth">] I got an understanding on how extends works but what I dont get is this method
def create(name) object = new(name) instances.push(object) return object end Specifically the line, instances.push(object)
Shouldn't it be @instances.push(object)
instances is a method in the module, how can we push objects to methods, it is not an array, it contains an array.
What is going on?
Please, I am new to Ruby, I will really appreciate simple answers.