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 如何定义和包含模块的主要内容,如果未能解决你的问题,请参考以下文章

ruby Ruby:如何创建一个包含相同方法的类和实例变体的模块

Ruby mixins:扩展和包含

使用 Ruby on Rails ActiveSupport::Concern 功能时如何“嵌​​套”包含模块?

如何选择要在 Ruby 中动态包含的模块版本?

Ruby:自定义 gem 需要其中的模块“要求”

Ruby 中的“包含模块”和“扩展模块”有啥区别? [复制]