什么时候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. 红宝石MatchData post_match意外行为
- 7. 执行红宝石
- 8. 红宝石拉姆达方面
- 9. 在红宝石
- 10. 在红宝石
- 11. 在红宝石
- 12. 在红宝石
- 13. 在红宝石
- 14. 在红宝石
- 15. 在红宝石
- 16. replica CSV.generate_line红宝石的行为1.8.7在红宝石1.9.2
- 17. 红宝石画面清晰
- 18. 自定义as_json红宝石
- 19. 红宝石消息自
- 20. 宝石安装红宝石
- 21. 调试宝石红宝石
- 22. Twitter的红宝石宝石
- 23. 红宝石宝石 - LoadError
- 24. 错误红宝石宝石
- 25. 卸载红宝石宝石
- 26. 红宝石宝石文档
- 27. 安装自己的宝石
- 28. 红宝石分配方法
- 29. 红宝石要求方法
- 30. 红宝石 - 方法问题
因为类和模块都是对象,'self'总是指当前目的。 – 2011-04-20 19:27:09