Search code examples
rubyinstance-variablesattr-accessor

Unable to access instance variable outside the class in ruby


In my code when trying to print p @stack outside the class,and it shows nil despite putting attr_accessor :stacks, :each_stack_size, :stack_number. As usual it works fine and shows data when using inside the class. What am i missing?

class SetOfStacks
 attr_accessor :stacks, :each_stack_size, :stack_number
 # Initializing Hash to hold all the stacks and initial stack is created.
 def initialize
  @stacks = Hash.new # declaring hash to hold all stacks
  @each_stack_size = 3 # defining each stack size
  @stack_number = 1 # Current stack number
  @stacks[@stack_number] = Array.new
 end
 ...
 ...

end 
@obj = SetOfStacks.new
@obj.push(4)
@obj.push(5)
@obj.push(6)
@obj.push(7)
@obj.pop
p @stacks

Solution

  • In order to print an instance variable, you must access it with the context of the instance.

    p @obj.stacks