Ruby self 通俗地说? [英] Ruby self in layman terms?

查看:35
本文介绍了Ruby self 通俗地说?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 什么时候引用对象,什么时候引用 Ruby 类?用例子解释会很棒.不明白这个.

When is Ruby self refering to the Object and when is self refering to the Ruby class? Explanations with examples would be great. Not getting my head around this.

推荐答案

类实际上是对象本身.假设我有一个 Person 类,它实际上是 Class 的一个实例.所以你可以让 self 引用一个 Article 的实例,或者你可以让 self 引用类的实例,Article.

Classes are actually objects themselves. Lets say that I have a class Person, this is actually an instance of Class. So you can have self refer to an instance of Article, or you can have self refer to the instance of the class, Article.

我能想到的最简单的例子:

In the most simple example I can think of:

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

要阅读有关自我的更多信息,强烈推荐阅读此内容.

To read more about about self, I highly recommend read this.

这篇关于Ruby self 通俗地说?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆