【发布时间】:2012-08-18 03:56:12
【问题描述】:
在 Ruby 中是否有引用类的当前实例的方法,就像 self 引用类本身一样?
【问题讨论】:
-
self确实指的是实例。你有具体的例子吗?
在 Ruby 中是否有引用类的当前实例的方法,就像 self 引用类本身一样?
【问题讨论】:
self 确实指的是实例。你有具体的例子吗?
可能你需要 :itself 方法?
1.itself => 1
'1'.itself => '1'
nil.itself => nil
希望对您有所帮助!
【讨论】:
(0..12).step(1).map(&:itself) 这样的更简洁的方法吗?
方法self 引用它所属的对象。类定义也是对象。
如果你在类定义中使用self,它指的是类定义的对象(到类),如果你在类方法中调用它,它又是指类。
但在实例方法中,它指的是作为类实例的对象。
1.9.3p194 :145 > class A
1.9.3p194 :146?> puts "%s %s %s"%[self.__id__, self, self.class] #1
1.9.3p194 :147?> def my_instance_method
1.9.3p194 :148?> puts "%s %s %s"%[self.__id__, self, self.class] #2
1.9.3p194 :149?> end
1.9.3p194 :150?> def self.my_class_method
1.9.3p194 :151?> puts "%s %s %s"%[self.__id__, self, self.class] #3
1.9.3p194 :152?> end
1.9.3p194 :153?> end
85789490 A Class
=> nil
1.9.3p194 :154 > A.my_class_method #4
85789490 A Class
=> nil
1.9.3p194 :155 > a=A.new
=> #<A:0xacb348c>
1.9.3p194 :156 > a.my_instance_method #5
90544710 #<A:0xacb348c> A
=> nil
1.9.3p194 :157 >
您会看到 puts #1 在类声明期间执行。它表明class A 是一个ID ==85789490 的Class 类型的对象。所以在类声明中 self 指的是类。
然后当类方法被调用时 (#4) self inside class method (#2) 再次引用该类。
当一个实例方法被调用时(#5)它表明在它内部(#3)self指的是该方法所附加的类实例的对象。
如果您需要在实例方法中引用类,请使用self.class
【讨论】:
self 引用始终可用,它指向的对象取决于上下文。
class Example
self # refers to the Example class object
def instance_method
self # refers to the receiver of the :instance_method message
end
end
【讨论】:
在类的实例方法中self 引用该实例。要在实例中获取类,您可以调用self.class。如果你在一个类方法中调用self,你就会得到这个类。在类方法中,您无法访问该类的任何实例。
【讨论】:
self 总是引用一个实例,但一个类本身就是Class 的一个实例。在某些情况下,self 会引用这样的实例。
class Hello
# We are inside the body of the class, so `self`
# refers to the current instance of `Class`
p self
def foo
# We are inside an instance method, so `self`
# refers to the current instance of `Hello`
return self
end
# This defines a class method, since `self` refers to `Hello`
def self.bar
return self
end
end
h = Hello.new
p h.foo
p Hello.bar
输出:
Hello
#<Hello:0x7ffa68338190>
Hello
【讨论】:
p self 实际上是在解析类定义时执行的。 h = Hello.new 实际上会返回与h.foo 相同的值。我提到这一点是为了以防列出的输出可能会误导一些新的 Rubyist。