首页 > 解决方案 > 查询 Ruby 模块

问题描述

我正在阅读一些教程,其中包含以下代码

module DecimalCode
  RED = "rgb(255,0,0)"
  GREEN = "rgb(0,128,0)"

  def code
    return "RED : Decimal code #{RED}"
  end


  def DecimalCode.code
    return "GREEN : Decimal code #{GREEN}"
  end

  def hello
    return "Hello world!"
  end

end

include DecimalCode
puts DecimalCode.hello
puts DecimalCode.code

我的疑问,

  1. code方法和方法有什么区别DecimalCode.code
  2. 当我不包含模块并键入它时,puts DecimalCode.code它总是打印Green: Decimal code,为什么会这样?

标签: ruby

解决方案


模块中的方法可以是实例方法或模块方法。当包含模块时,实例方法作为类中的方法出现,而模块方法则没有。

这里code称为模块中的实例方法,而DecimalCode.code称为模块方法。


推荐阅读