我正在编写这样的程序:
module Filter
def self.included?(klass)
@count = 0
end
end
class Object
include Filter
end
class Person
def get_count
puts @count
end
end
我想通过mixin Filter定义一个实例变量@count,希望这个mixin可以被所有Object访问。
但是,我的方法行不通。
谁能告诉我如何实现这个目标?
最佳答案
不要使用变量,使用属性:
module Counter
attr_accessor :count
end
class Person
include Counter
end
person = Person.new
person.count = 50
puts person.count
此外,不要将内容包含在 Object
中,仅包含在您的类中。用非通用方法污染主命名空间是不好的,可能会导致其他类中的方法名称冲突,从而导致难以发现的错误。
仅在您认为需要的地方包含模块,而不是在所有地方包含模块。
关于ruby - 如何通过mixin定义实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12158980/