Ruby 模块和自我扩展
在什么样的情况下使用代码:
module M
extend self
def greet
puts "hello"
end
end
比这样说更有利:
module M
def self.greet
puts "hello"
end
end
在顶部,一个是扩展的实例方法,后者只是一个类方法,但是在调用任一方法时,您都必须M.打招呼,对吧?我只是好奇是否有人可以阐明何时使用一种代码而不是另一种代码。谢谢!
In what sort of situation is the code:
module M
extend self
def greet
puts "hello"
end
end
more beneficial to use over say something like:
module M
def self.greet
puts "hello"
end
end
In the top, one is an instance method being extended, and the latter is just a class method, but when calling either method, you'd have to M.greet , right? I was just curious if anyone could shed some light on when to use one code over the other. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第一个示例通常是人们实现 module_function 功能的一种方式(当他们不知道此方法的存在时)。
module_function
既是实例方法又是类方法。在第二个代码示例中,该方法只是一个类方法。The first example is typically a way people achieve the functionality of
module_function
(when they do not know the existence of this method).A
module_function
is both an instance method and a class method. In your second code example the method is just a class method.可以用您的第一个示例来执行此操作,但不能用第二个示例来执行此操作:
It would be possible to do this with your first example, but not your second:
模块可以通过编写模块方法用作命名空间,并且模块的实例方法可以混合到另一个对象中。
自扩展模块概念允许模块以两种方式使用;作为独立的命名空间或作为 mixin。考虑这个模块:
它有一个实例方法,可以混合到另一个对象中。它没有模块方法,因此不能用作命名空间:
但是,模块只是类
Module
的一个对象,正如我们可以演示的那样,这意味着我们可以做一些疯狂的事情。我们可以将模块混合到其自身中,使其方法既成为实例方法又成为模块方法。
A module can be used as a namespace by writing module methods, and a module's instance methods can be mixed into another object.
The self-extending module concept allows a module to be used in both ways; either as a stand-alone namespace or as a mixin. Consider this module:
It has an instance method and can be mixed in to another object. It does not have a module method and cannot, therefore be used as a namespace:
But, a module is an just an object of class
Module
, as we can demonstrateThis means that we can do something crazy. We can mix a module into itself so that its methods become both instance and module methods.