Ruby 类<&书信电报;模中的符号
我试图将一个模块混合到一个类中,我希望其中一些方法可以作为类方法,而另一些方法可以作为实例方法 但是,我不想同时包括Ruby 类<&书信电报;模中的符号,ruby,module,metaprogramming,mixins,Ruby,Module,Metaprogramming,Mixins,我试图将一个模块混合到一个类中,我希望其中一些方法可以作为类方法,而另一些方法可以作为实例方法 但是,我不想同时包括和扩展模块。我宁愿把它包括在内 当我将我希望成为类方法的方法包装在这个符号中时,它可以工作: class << # ... end 是的,如果你想在你的模块中得到一个真正的自我,你应该使用包含的。类似这样的东西会为你指明正确的方向: module Bar def self.included(base) class << base
和扩展模块。我宁愿把它包括在内
当我将我希望成为类方法的方法包装在这个符号中时,它可以工作:
class <<
# ...
end
是的,如果你想在你的模块中得到一个真正的自我
,你应该使用包含的。类似这样的东西会为你指明正确的方向:
module Bar
def self.included(base)
class << base
def class_method
"class_method"
end
end
end
end
class Foo
include Bar
end
p Foo.class_method # => "class_method"
模块条
def自带(基本)
类“类方法”
课堂哈,我错过什么了吗<代码>课堂我相信这就是他想要实际解决问题的方法,但这并不能回答像@sepp2k这样的课堂所说的课堂感谢纳什,我知道包含的方法,但发现离开自我似乎也能达到类似的效果。我没有遇到语法错误,并且已经在ruby 1.8和1.9.3中尝试过——我将在稍后发布一个完整的代码示例供其他人尝试。我使用的是1.9.2,我可以重现Nathan的问题。如果我在做class Lol时使用class@ChrisRice,这就解释了为什么“明显的”类方法需要在Object中才能工作。它实际上是一个单例实例方法。干得好。
module M
class <<
def class_method
puts "From inside the class_method"
end
end
def instance_method
puts "From inside the instance_method"
end
end
class Object
include M
end
class C
end
C.class_method
obj = C.new
obj.instance_method
module Bar
def self.included(base)
class << base
def class_method
"class_method"
end
end
end
end
class Foo
include Bar
end
p Foo.class_method # => "class_method"
class <<
def class_method
puts "From inside the class_method"
end
end
class << def class_method
puts "From inside the class_method"
end
end
temp = def class_method
puts "From inside the class_method"
end
class << temp
end
def class_method
puts "From inside the class_method"
end
class << nil
end
def class_method
puts "From inside the class_method"
end