user273072545345
user273072545345

Reputation: 1566

Confusion on instance variable as opposed to lack of it

Came across this code from 'The Grounded Rubyist'

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

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

  def take_from_stack
    stack.pop
  end
end

as opposed to:

class Stack

 attr_reader :stack

 def initialize
  @stack = [] 
 end 

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

 def take_from_stack
  @stack.pop
 end
end

My primary confusion stems from the fact that in the module, the instance variable @stack is not in add_to_stack and take_from_stack methods. How is the state of the stack tracked otherwise?

In the class, @stack is used in all methods which is the norm I'm used to.

Can someone explain how this works in the module?

Upvotes: 0

Views: 31

Answers (1)

Leo Brito
Leo Brito

Reputation: 2051

in the module, the instance variable @stack is not in add_to_stack and take_from_stack methods. How is the state of the stack tracked otherwise?

Not quite. add_to_stack pushes something on @stack, because the stack method returns @stack:

  def stack
    @stack ||=[]
  end

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

So in the end, @stack is used in add_to_stack.

Note that you could safely remove the @s from all @stack in class Stack (except the assignment in initialize), because attr_reader :stack defines a stack method that returns @stack.

Upvotes: 2

Related Questions