如何在Ruby中为类变量编写一个编写器方法?
问题描述:
我正在学习Ruby,我的大脑刚刚冻结。如何在Ruby中为类变量编写一个编写器方法?
在下面的代码中,我将如何为'self.total_people'编写类写入器方法?我正在“计数”班级“人物”的实例数量。
class Person
attr_accessor :name, :age
@@nationalities = ['French', 'American', 'Colombian', 'Japanese', 'Russian', 'Peruvian']
@@current_people = []
@@total_people = 0
def self.nationalities #reader
@@nationalities
end
def self.nationalities=(array=[]) #writer
@@nationalities = array
end
def self.current_people #reader
@@current_people
end
def self.total_people #reader
@@total_people
end
def self.total_people #writer
#-----?????
end
def self.create_with_attributes(name, age)
person = self.new(name)
person.age = age
person.name = name
return person
end
def initialize(name="Bob", age=0)
@name = name
@age = age
puts "A new person has been instantiated."
@@total_people =+ 1
@@current_people << self
end
答
您可以通过附加等号方法名的最后一个定义:
def self.total_people=(v)
@@total_people = v
end
你把所有实例@@ current_people你可以更准确地定义total_people:
def self.total_people
@@current_people.length
end
并摆脱所有与@@ total_people相关的代码。
没有工作
答
一种方法是如下:
module PersonClassAttributes
attr_writer :nationalities
end
class Person
extend PersonClassAttributes
end
我怀疑这是因为attr_writer不会出于某种原因模块工作。
我想知道是否有一些元编程方法来解决这个问题。但是,您是否考虑过创建一个包含人员列表的对象?
答
我认为这能解决你的问题:
class Person
class << self
attr_accessor :foobar
end
self.foobar = 'hello'
end
p Person.foobar # hello
Person.foobar = 1
p Person.foobar # 1
注意用Ruby与继承类变量的陷阱中 - 子类不能覆盖类变种的父级的值。 A class instance variable可能真的是你想要的,而这个解决方案就是朝着这个方向发展的。