ruby - 查询 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
我的疑问,
code
方法和方法有什么区别DecimalCode.code
- 当我不包含模块并键入它时,
puts DecimalCode.code
它总是打印Green: Decimal code
,为什么会这样?
解决方案
模块中的方法可以是实例方法或模块方法。当包含模块时,实例方法作为类中的方法出现,而模块方法则没有。
这里code
称为模块中的实例方法,而DecimalCode.code
称为模块方法。
推荐阅读
- pandas - pandas:比较df中的两列,返回跨行的组合值范围
- php - WampServer 3.2.3 无法访问局域网,
- python - .env 从 CLI 运行时未加载,但从 VSCode 运行时
- go - 如何使用 pgx 记录查询?
- javascript - 使用 XMLHttpRequest,我正在尝试建立一个旁边有评论的博客
- python - 来自 scipy 的 jarque_bera 计算
- android - KeyEvents在android中的文本之后没有占用空间
- c# - 使用自定义方法结合 Where 和 OrderByDescending
- sql - 这是一个 Sql-Server 查询,如何在 Postgresql 中执行?
- java - Quarkus 和 Redis