0

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
Rahul Dess
  • 2,397
  • 2
  • 21
  • 42

2 Answers2

2

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

p @obj.stacks
ianks
  • 1,708
  • 19
  • 15
  • 1
    Your answer will work, but your explanation is incorrect. Invoking `@obj.stacks` invokes the getter method within @obj; it only *looks* like you have direct access to the instance variable. – Todd A. Jacobs Oct 09 '14 at 05:56
  • Yes you are correct. I simplified my answer a bit to get the point across. When you set attr_accessor, you are creating both 'getter' and 'setter' methods which allow you to read, and write to instance variables, respectively. If, for example, you only want to allow read access to an instance variable, you can set attr_reader. Although that does not purely hold true because we can override that and call instance_variable_set on the object. – ianks Oct 09 '14 at 06:07
2

Getter and Setter Methods

You're misunderstanding what Module#attr_accessor does. Essentially, it creates getter and setter methods for your instance variables. In your case, attr_accessor :stacks creates the SetOfStacks#stacks and SetofStacks#= methods. Note that these are still instance methods of your object, not global variables, so you still have to invoke them properly. For example:

@obj = SetOfStacks.new
@obj.stacks                # invoke your getter
@obj.stacks = { foo: nil } # invoke your setter
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199