ruby – 类<<模块中的符号
发布时间:2020-12-17 03:21:51 所属栏目:百科 来源:网络整理
导读:我正在尝试将一个模块混合到一个类中,我想要一些方法作为类方法,其他方法作为实例方法. 但是,我不想同时包含和扩展模块.我宁愿把它包括在内. 当我用这种表示法包装我想成为类方法的方法时,它可以工作: class # ...end 但是,当我使用这种表示法时,它不起作用
我正在尝试将一个模块混合到一个类中,我想要一些方法作为类方法,其他方法作为实例方法.
但是,我不想同时包含和扩展模块.我宁愿把它包括在内. 当我用这种表示法包装我想成为类方法的方法时,它可以工作: class << # ... end 但是,当我使用这种表示法时,它不起作用: class << self # ... end 我怀疑self关键字是建立一个与模块的显式绑定,而不是它混入的类.但我没有看到任何建议在使用类<<<<<<<<符号. 有谁知道这是怎么回事? 更新:以下是一些示例代码,以便更清晰: 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 解决方法
class<<必须始终跟一个对象.只是班级<< ;;结束是语法错误.在你的情况下它看起来像是有效的,因为以下内容:
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 当然,这实际上并没有定义一个类方法.它定义了一个实例方法. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |