Ruby如何从同一命名空间中的类调用模块方法

Ruby如何从同一命名空间中的类调用模块方法,ruby,mixins,Ruby,Mixins,我是Ruby新手,试图理解Ruby中的模块方法 module M1 def comments if @comments @comments else @comments = [] end end def add_comment(comment) comments << comment end class Audio <<How

我是Ruby新手,试图理解Ruby中的模块方法

module M1
    def comments 
      if @comments
        @comments
      else
        @comments = []
      end
    end

    def add_comment(comment)
       comments << comment
    end

    class Audio

         <<How do i call add_comment or comments >>
         def someMethod
            add_comment "calling module method from class which is in  same namespace or module"
         end

    end

end
模块M1
def评论
如果@comments
@评论
其他的
@评论=[]
结束
结束
def添加注释(注释)

注释通常,您可以使用惰性初始值设定项来解决此问题:

其中,除非已定义,否则将使用空数组填充
@comments

这使得
add_comment
方法变得多余,因为您只需执行以下操作:

comments << comment
现在您可以执行以下操作:

M1.comments << 'New comment'

M1.comments我真的不明白你想做什么。也许您可以使用
self.add\u comment
声明一个类方法,然后从您的实例调用它作为
M1.add\u comment
。模块可能包含两种方法:模块方法和实例方法。前者在模块
M
上定义为
def M.mm…end
或更常见的是,在模块内定义为
def self.mm…end
。在模块上调用这些函数(例如
Math.sqrt(10)
)。实例方法——您的示例中的方法——需要类
C
的实例作为它们的接收者,因此必须是
C
的实例方法。后者只能通过从
C
内部(或从
C
的祖先)执行
C.include M
include M
来实现。如果
M
包含在
C
中,则传递
M
中的任何模块方法。
def self.comments 
  @comments ||= [ ]
end
M1.comments << 'New comment'