Instance variables in modules?

module, ruby

Solution

Think of the instance variable as something which will exist in any class that includes your module, and things make a bit more sense:

module Stacklike
  def stack
    @stack ||= []
  end

  def add_to_stack(obj)
    stack.push(obj)
  end

  def take_from_stack
    stack.pop
  end
end

class ClownStack
  include Stacklike

  def size
    @stack.length
  end
end

cs = ClownStack.new
cs.add_to_stack(1)
puts cs.size

will output "1"

Problem

How is it possible that I can have instance variables in a module even though I cannot create an instance of the module? What would be the purpose of `@stack` in module `Stacklike` below? ``` module Stacklike def stack @stack ||= [] end end ```

Original source