像实例一样的"self"之类的Ruby方法 [英] Ruby method like `self` that refers to instance

查看:82
本文介绍了像实例一样的"self"之类的Ruby方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby中是否有一个方法引用类的当前实例,就像self引用该类本身一样?

Is there a method in Ruby that refers to the current instance of a class, in the way that self refers to the class itself?

推荐答案

self始终引用实例,但是类本身就是Class的实例.在某些情况下,self将指代这样的实例.

self always refers to an instance, but a class is itself an instance of Class. In certain contexts self will refer to such an instance.

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

这篇关于像实例一样的"self"之类的Ruby方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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