当程序需要在程序的某个时间点上而不是在intialize方法中设置或改变一个对象的状态,如何给实例变量赋值,这是可以用setter方法解决。
代码:
class Teacher
def initalize(name,date)
@name=name
@date=date
end
def set_color(color)
@color=color
end
end
teachea=Teacher.new("Wfeng","11/12/13")
teacher.set_color("red")
这里实例变量@color 在setter方法 set_color,可以随时重新赋值。
ruby-setter方法
最新推荐文章于 2025-02-04 15:36:29 发布