Ruby 中的 self 是什么意思? [英] What does self mean in Ruby?

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

问题描述

ruby self 代表什么?它是什么?这是什么意思?有人可以向我解释一下吗?简单来说,请它在类中的作用是什么?

What does ruby self represent? what is it? what does it mean? Could some please explain it to me? in simple terms please And what is its function in a class?

class MyClass
   def method.self
   end
end

推荐答案

self 指的是当前在上下文中的对象.

self refers to the object that is currently in context.

在您的示例中,selfclass 本身,def self.method 正在定义一个类方法.例如:

In your example, self is the class itself and def self.method is defining a class method. For example:

class MyClass
  def self.method
    puts "Hello!"
  end
end

> MyClass.method
#=> "Hello"

您还可以在类的实例上使用 self.

You can also use self on instances of a class.

class MyClass
  def method_a
    puts "Hello!"
  end

  def method_b
    self.method_a
  end
end 

> m = MyClass.new
> m.method_b
#=> "Hello!"

在这种情况下,self 指的是 MyClass 的实例.

In this case, self refers to the instance of MyClass.

Ruby 中的自我 上有一篇很好的博客文章,或者,正如评论中指出的那样,Ruby 文档.

There is a good blog post on self in Ruby here, or, as it was pointed out in the comments, there is some more on this in the Ruby documentation.

这篇关于Ruby 中的 self 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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