Ruby在外行中的表现?
什么时候Ruby自我引用了Object,什么时候自我引用Ruby类? 用例子解释会很棒。 没有理解这个。
类实际上是对象本身。 可以说我有一个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
要阅读有关自我的更多信息, 我强烈建议您阅读本文。
我可以尝试自己解释一下,但我认为Yehuda Katz比我做得更好:
Ruby中的元编程:它是关于自我的全部
我的理解是
- 在您定义类方法或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
改为接收者。
- 在ruby / ActiveRecord中生成类似Instagram或Youtube的不可语句字符串ID
- 尝试在Windows XP中使用Heroku时找不到msvcrt-ruby18.dll
- 在debian Squeeze上安装RoR
- 如何阻止Savon为soap.body添加前缀
- 定义“method_called”..如何调用每次调用类的任何函数时调用的钩子方法?
- AbstractController :: CommentsController中的DoubleRenderError #create
- 为什么当字符串包含数字时,Ruby的String#to_i有时会返回0?
- 方法给出ActiveRecord :: Relation错误?
- 什么样的ruby方法调用是Array(x)