【发布时间】:2014-12-03 22:46:39
【问题描述】:
在我的代码中尝试在课堂外打印p @stack 时,尽管放置了attr_accessor :stacks, :each_stack_size, :stack_number,但它显示nil。像往常一样,它工作正常,并在类内使用时显示数据。我错过了什么?
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
【问题讨论】:
-
你知道instance变量是什么意思吗?
-
在您的
initialize方法中,您也可以使用self.stacks = Hash.new,因为attr_accessor用于创建getter 和setter 方法。 -
如果你只是想用
@引用你的实例变量(在你的类中),你不需要使用attr_accessor。
标签: ruby instance-variables attr-accessor