是否可以在ruby中的模块中声明静态方法?
module Software
def self.exit
puts "exited"
end
end
class Windows
include Software
def self.start
puts "started"
self.exit
end
end
Windows.start
Run Code Online (Sandbox Code Playgroud)
上面的例子不会打印出"退出".
是否只能在模块中使用实例方法?
mik*_*kej 32
像这样定义你的模块(即exit在模块中创建一个实例方法):
module Software
def exit
puts "exited"
end
end
Run Code Online (Sandbox Code Playgroud)
然后使用extend而不是include
class Windows
extend Software
# your self.start method as in the question
end
Run Code Online (Sandbox Code Playgroud)
正在使用:
irb(main):016:0> Windows.start
started
exited
=> nil
Run Code Online (Sandbox Code Playgroud)
说明
obj .extend(module,...)将 obj作为参数给出的每个模块的实例方法添加到 obj中
...因此,当在类定义的上下文中使用(类本身作为接收者)时,方法将成为类方法.
Way*_*rad 18
将您的类方法放在嵌套模块中,然后覆盖"包含"钩子.只要包含模块,就会调用此挂钩.在钩子内部,将类方法添加到包含的任何人:
module Foo
def self.included(o)
o.extend(ClassMethods)
end
module ClassMethods
def foo
'foo'
end
end
end
Run Code Online (Sandbox Code Playgroud)
现在任何包括Foo的类都会得到一个名为foo的类方法:
class MyClass
include Foo
end
p MyClass.foo # "foo"
Run Code Online (Sandbox Code Playgroud)
任何非类方法都可以像往常一样在Foo中定义.