Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
这有什么问题set/get?
set/get
class Pupil def name @name end def name=(name) @name = name end def age @age end def age=(age) @age end end
同样,如果有一个具有 3 个参数的子类,名称、年龄、性别,那么子类中的 set get 方法是否仅用于性别。您能否显示 set/get 方法并在子类中初始化。
def age=(age) @age end
应该
def age=(age) @age = age end
您还可以通过将 get/set 替换为 attr_accessor 来使您的代码更漂亮,attr_accessor 本身提供了一个 getter/setter
class Pupil attr_accessor :age,:name end
你忘了设置@age = age。
@age = age