gpt4 book ai didi

ruby - 我可以从同一个模块添加类方法和实例方法吗?

转载 作者:数据小太阳 更新时间:2023-10-29 06:56:23 25 4
gpt4 key购买 nike

新手问题:

我知道 include 和 extend 是如何工作的,我想知道是否有办法从单个模块中同时获取类和实例方法?

这就是我使用两个模块的方式:

module InstanceMethods
def mod1
"mod1"
end
end

module ClassMethods
def mod2
"mod2"
end
end

class Testing
include InstanceMethods
extend ClassMethods
end

t = Testing.new
puts t.mod1
puts Testing::mod2

感谢您抽出宝贵时间...

最佳答案

有一个常见的成语。它使用included 对象模型钩子(Hook)。每次将模块包含到模块/类中时都会调用此 Hook

module MyExtensions
def self.included(base)
# base is our target class. Invoke `extend` on it and pass nested module with class methods.
base.extend ClassMethods
end

def mod1
"mod1"
end

module ClassMethods
def mod2
"mod2"
end
end
end

class Testing
include MyExtensions
end

t = Testing.new
puts t.mod1
puts Testing::mod2
# >> mod1
# >> mod2

我个人也喜欢将实例方法分组到一个嵌套模块中。但据我所知,这种做法不太被接受。

module MyExtensions
def self.included(base)
base.extend ClassMethods
base.include(InstanceMethods)

# or this, if you have an old ruby and the line above doesn't work
# base.send :include, InstanceMethods
end

module InstanceMethods
def mod1
"mod1"
end
end

module ClassMethods
def mod2
"mod2"
end
end
end

关于ruby - 我可以从同一个模块添加类方法和实例方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16525402/

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