【发布时间】:2013-09-21 05:19:48
【问题描述】:
在初始化类中的变量(实例变量等)时遇到了一些麻烦,我想知道是否有人可以为我澄清正确的语法。
示例代码:
Class Pets
attr_accessor :name
def initialize(name)
@name=name
end
def name=(name)
@name = name
#I believe this is where I change @name instance variable
end
#in this space I could create more <methods> for Class.new.<method>
end
我的问题是我需要attr_accessor 以及def initialize 和def name= 吗?
此外,如果我有多个 attr_accessor,是否需要将它们作为参数添加到 def initialize,例如:
Class Pets
attr_accessor :name :age :color
def initialize(name, age, color)
@name = name
@age = age
@color = color
#and if this is the case do I need methods for each (name= age= color= etc.)
end
最后一件事:
如果有人可以确认或否认我对类中 name= age= 和 color= 类型的方法的思考过程。我认为method= 有必要更改实例变量是否正确?我有点不确定method= 的用途以及为什么我不能在初始化中更改实例变量。
【问题讨论】:
标签: ruby class initialization instance-variables