[英]Methods defined in class Object are instance and class one at the same time
How can be described that a method boo defined in Object class becomes instance and class one at the same time in class Foo ? 如何描述在Object类中定义的方法boo同时在类Foo中成为实例和类一?
class Foo; end
class Object
def boo
'boo method'
end
end
p Foo.boo # => boo method
p Foo.new.boo # => boo method
If you really want to do this, keep in mind that the class context and the instance context are entirely different so instance variables are not equivalent. 如果确实要执行此操作,请记住,类上下文和实例上下文完全不同,因此实例变量不是等效的。
module FooMethods
def boo
'boo'
end
end
class Foo
extend FooMethods
include FooMethods
end
This deliberately imports the mixin at both the class level via extend
and instance level via include
. 这故意通过extend
在类级别和通过include
实例级别导入mixin。
Perhaps forwarding the method to self
is an option? 也许将方法转发给self
是一种选择?
require 'forwardable'
class Foo
extend Forwardable
def self.boo
'boo method'
end
def_delegator self, :boo
end
Foo.boo
#=> "boo method"
Foo.new.boo
#=> "boo method"
Every object is an instance of Object
. 每个对象都是Object
一个实例。 Thus, every object will respond to boo
. 因此,每个对象都将响应boo
。
Foo
is an object (classes are objects, too), ergo, Foo
is an instance of Object
(it is an instance of Class
, which is a subclass of Module
, which is a subclass of Object
). Foo
是一个对象(类也是对象),因此, Foo
是Object
的实例(它是Class
的实例,它是Module
的子类,后者是Object
的子类)。
Foo.new
is an object (it is an instance of Foo
, which is a subclass of Object
). Foo.new
是一个对象(它是Foo
的实例,它是Object
的子类)。
Since both Foo
and Foo.new
are instances of Object
, both respond to boo
. 由于Foo
和Foo.new
都是Object
实例,因此两者都响应boo
。
[Note: I am ignoring the existence of BasicObject
.] [注意:我忽略了BasicObject
的存在。]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.