ruby 如何定义和包含模块

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 如何定义和包含模块相关的知识,希望对你有一定的参考价值。

# module name is a constant
module Debug
  
  # constant will not be mixin
  LEVEL = 'error'
  
  # instance variable.
  # It may clash with those of the host class or with those of other mixins.
  # For the most part, mixin doesn't use instance variables directly, they use accessors of hosts.
  attr_accessor :message
  
  # instance method
  def whois
    #{self.class.name}"
  end
  
end


class Apple
  # mixin a module use `include`
  include Debug
end

apple = Apple.new

# access mixin method
p apple.whois #=> Apple 

# access mixin instance variable
# Again, a module has its own state is not a mixin, it should be written as a class.
apple.message = 'Google'
p apple.message #=> Apple

以上是关于ruby 如何定义和包含模块的主要内容,如果未能解决你的问题,请参考以下文章