什么时候Ruby自引用对象,什么时候自引用到Ruby类?用例子来解释会很棒。没有得到我的头在这附近。红宝石自己在外行方面?
4
A
回答
5
类实际上是对象本身。假设我有一个类Person
,这实际上是Class
的一个实例。所以你可以自己引用Article的实例,或者你可以自己引用类的实例Article
。
在最简单的例子,我能想到的:
class Person
def initialize
p "Info about Person Instance"
p self
p self.class
end
p "Info about Person Class"
p self
p self.class
end
person = Person.new
它打印:
"Info about Person Class"
Person
Class
"Info about Person Instance"
#<Person:0x0000010086cf58>
Person
想了解更多关于关于自我,I highly recommend read this.
2
我的理解是
- Environm您正在定义类方法或module_functions,
self
指的是类/模块。 - 在您定义实例方法的环境中,
self
引用该实例。
例如,
class A
def method1
self # => instance of A
end
def self.method2
self # => class A
endu
def A.method3
self # => class A
end
end
class << A
def method4
self # => class A
end
end
module B
module_function
def method5
self # => module B
end
end
例外是instance_eval
,instance_exec
改变self
到接收器。
3
相关问题
- 1. 红宝石自己执行
- 2. 红宝石自己放
- 3. 修改自己,红宝石
- 4. 把自己得到的红宝石
- 5. 红宝石插座连接到外面
- 6. 有没有更好的方式不重复自己(红宝石)?
- 7. 红宝石``**方法
- 8. 红宝石:方法
- 9. 红宝石散列在红宝石
- 10. 红宝石 - 在类方法
- 11. 执行红宝石
- 12. 红宝石MatchData post_match意外行为
- 13. 亚行外壳和红宝石
- 14. 红宝石拉姆达方面
- 15. 在红宝石
- 16. 在红宝石
- 17. 在红宝石
- 18. 在红宝石
- 19. 在红宝石
- 20. 在红宝石
- 21. :在红宝石
- 22. 在红宝石
- 23. 在红宝石
- 24. 在红宝石
- 25. 在红宝石
- 26. 在红宝石
- 27. 在红宝石
- 28. 在红宝石
- 29. replica CSV.generate_line红宝石的行为1.8.7在红宝石1.9.2
- 30. 红宝石宝石命令行工具
因为类和模块都是对象,'self'总是指当前目的。 – 2011-04-20 19:27:09