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 
4
  • You know what instance variable means, do you? Commented Oct 9, 2014 at 5:43
  • In your initialize method, you could also do self.stacks = Hash.new because attr_accessor is for creating getter and setter methods. Commented Oct 9, 2014 at 5:55
  • 1
    You don't need to use attr_accessor if you simply want to reference your instance variables (inside your class) with an @. Commented Oct 9, 2014 at 5:56
  • Related Q&A: stackoverflow.com/q/12122736/1301972 Commented Oct 9, 2014 at 6:55

2 Answers 2

2

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

p @obj.stacks 
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.