在Ruby模块上查询

时间:2019-01-04 05:39:09

标签: 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. 方法codeDecimalCode.code之间有什么区别
  2. 当我不包括该模块并键入puts DecimalCode.code时,它总是打印Green: Decimal code,为什么会这样?

1 个答案:

答案 0 :(得分:0)

模块中的方法可以是实例方法或模块方法。当包含模块时,实例方法在类中显示为类中的方法,而模块方法则不显示。

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