Ruby 其中定义了允许执行的方法和运算符;类<&书信电报;自己德福;结束;完";内部类定义?
这是怎么解释的?我可以用其他对象替换self吗?这个语法在ruby中用于访问对象的元类或单例类。元类用于存储单个对象的方法Ruby 其中定义了允许执行的方法和运算符;类<&书信电报;自己德福;结束;完";内部类定义?,ruby,Ruby,这是怎么解释的?我可以用其他对象替换self吗?这个语法在ruby中用于访问对象的元类或单例类。元类用于存储单个对象的方法 obj = # whatever... class <<obj # here, self is defined as obj's metaclass # so foo will be an instance method of obj's metaclass # meaning that we can call obj.foo def foo
obj = # whatever...
class <<obj
# here, self is defined as obj's metaclass
# so foo will be an instance method of obj's metaclass
# meaning that we can call obj.foo
def foo
# ...
end
end
# this is equivalent to the above
def obj.foo
# ...
end
obj=#随便。。。
类使用该语法添加类方法,这些方法在类上调用,而不是在该类的特定实例上调用
例如:
class Foo
class << self
def do_foo
# something useful
end
end
end
另请参见《为什么》对元类的解释:
同样关于“self”和替换它,我已经看到它提到了其他一些地方——我很难为该特性想出一个好的用例,尽管它肯定会让我困惑。也许有一个。在任何情况下,尝试更改“self”的值在Ruby中都是无效的语法:
在Ruby中,以及在所有其他具有“self”或“this”概念的语言中,它被用作指向“here”的指针,如在当前对象、类或元类中,或者表示“here”含义的任何对象中。由于Ruby是逐行解释的,“self”表示编译器遇到该关键字时的封闭对象
class Array
self # Means Array class (which is an object, actually)
def self.class_method
self # still means Array class, since you're in a class method
end
def hello
self # Means the current instance of Array
end
class << self
self # Means the metaclass (or "eigenclass") of the Array
end
end
类数组
self#表示数组类(实际上是一个对象)
def self.class_方法
self仍然意味着数组类,因为您使用的是类方法
结束
你好
self#表示数组的当前实例
结束
类我认为jtr意味着在类中使用不同的对象,而不是self
>> self = Object.new
SyntaxError: compile error
(irb):1: Can't change the value of self
self = Object.new
^
from (irb):1
from :0
class Array
self # Means Array class (which is an object, actually)
def self.class_method
self # still means Array class, since you're in a class method
end
def hello
self # Means the current instance of Array
end
class << self
self # Means the metaclass (or "eigenclass") of the Array
end
end