gpt4 book ai didi

ruby - 类的实例方法与模块方法

转载 作者:数据小太阳 更新时间:2023-10-29 07:47:54 27 4
gpt4 key购买 nike

我正在阅读这篇关于 Ruby 模块方法的解释,以及它们与类的实例方法有何不同。这是我正在阅读的解释:

Remember that unlike an instance method, a module method needs to be defined on the module itself. How do you access the module? Recall that inside a module definition, self refers to the module being defined. So you'll need to define the method using the form self.xxx.

我不是很明白。当我们在类中定义方法时,我们不必在类本身上定义它。我们只是在类的实例化对象上调用它。

为什么我们需要使用术语“self”在模块本身上定义模块方法?这样做的目的是什么?为什么我们不能只定义模块方法而不使用术语 self?这是我的模块骨架的样子:

module GameTurn

def self.take_turn(player)

end

最佳答案

有两种模块方法:

  • 那些旨在混合到其他模块或类中的:“Mixins”
  • 那些打算直接使用的:“公开的方法”

例如:

module Example
def self.exposed_method
# This method is called as Example.exposed_Method
end

def mixin_method
# This method must be imported somewhere else with include or extend
# or it cannot be used.
end
end

你在 class 上也有两个:

  • 那些只在类的实例上调用的:“实例方法”
  • 那些直接在类上调用的:“类方法”
    • 这些在其他语言中也称为“静态方法”。

例子:

class ExampleClass
def self.class_method
# This can be called as ExampleClass.class_method
end

def instance_method
# This can only be called on an instance: ExampleClass.new.instance_method
end
end

关于ruby - 类的实例方法与模块方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26514370/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com