在这些方法中Math可被调用等一类的方法:
Math.cos(0)
Run Code Online (Sandbox Code Playgroud)
但也可以include像实例方法一样:
include Math
cos(0)
Run Code Online (Sandbox Code Playgroud)
相反,可以以一种方式调用以下模块,而不是另一种方式:
module Foo
def bar
end
end
Foo.bar() # NoMethodError for this call
include Foo
bar() # but this call is fine
Run Code Online (Sandbox Code Playgroud)
单身方法:
module Foo
def self.bar
end
end
Foo.bar() # this call is fine
include Foo
bar() # but not this one
Run Code Online (Sandbox Code Playgroud)
知道怎么写模块怎么样Math?
nil*_*nil 12
有几种方法可以获得单例方法,所以我将首先考虑这些方法.我们将include Math在一分钟内完成工作.所以,首先,如果你在一个模块或类体中,你可以将一个单例方法定义为一个方法self,如下所示:
module Foo
# Define bar as a method on self (the Foo module), thereby making
# it a singleton method.
def self.bar
"baz"
end
end
Run Code Online (Sandbox Code Playgroud)
或者,您可以将它们定义为模块或类的单例类上的方法:
module Foo
# Opens the singleton class of self (the Foo module). This makes
# bar a singleton method (see Module#define_singleton_method for
# some more on that).
class <<self
def bar
"baz"
end
end
end
Run Code Online (Sandbox Code Playgroud)
include Math,有你的方法,并吃他们第三,如果你想将方法作为实例和单例方法,你可以使用extend.这允许您将模块包含在某处并且无需限定地调用其方法,或至少具有不同的限定条件,具体取决于您包含模块的位置(但是,这超出了此范围).您还extend self可以使用另一个模块(包含实例方法)进行扩展,以便在模块或类体中将它们作为单例方法添加.这可能听起来比看起来更复杂:
module Foo
def bar
"baz"
end
# Extending self will add the instance methods of self as
# methods on the object self -- which happens to be a module,
# so you basically get class methods from the instance methods.
extend self
end
Run Code Online (Sandbox Code Playgroud)
这最后一种情况还允许您include在另一个模块或类和增益模块bar作为一个实例方法一样,所以什么你做取决于你所需要的东西.一般来说,如果我只是定义一个单例方法,我更喜欢第一条路线,这就是我所需要的.第二个选项或多或少相同,但也允许您使用alias_method等等.就我而言,合格的访问权与敬虔相关.
然而,第三种选择 - 使用extend self- 有利于做你所要求的事情include Math,你希望能够将一个函数作为单例方法调用(Math.cos(0))并包含模块来访问和调用方法而不需要限定它们带有模块名称(cos(0)).如果您需要,可以执行以下操作之一:
extend self.扩展使用self可能是这里的最佳选择,因为它很简单,减少了重复代码,并且足以满足问题的目的.所以你去,实例方法和单身方法和谐地生活在一起,就像Holan和Hamlet一样.