Ruby中的自我是什么意思?(复制) - What does self mean in Ruby? [duplicate]

- 此内容更新于:2016-02-01
主题:

这个问题已经有了一个答案:Ruby的自我定义3答案Ruby代表什么?它是什么?这是什么意思?一些能给我解释一下吗?简而言之,请其功能在一个类是什么?

原文:

This question already has an answer here:

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
网友:你在哪里看到这段代码?我认为是不恰当的。:)请阅读这个博客了解自我。

(原文:Where you saw this piece of code? I think, self is misplaced.. :) Please read through this blog to understand what is self ..)

网友:它是用Ruby文档-ruby-doc.org/docs/keywords/1.9/Object.html#method-i-self解释道。看一看如何问一个问题,确保你已经做了充分的研究和具体问题。

(原文:It is explained in Ruby Documentation- ruby-doc.org/docs/keywords/1.9/Object.html#method-i-self. Have a look at How to ask a question and make sure that you have done sufficient research and post specific question.)

网友:@WandMaker帮助我们关闭这个问题..:)

(原文:@WandMaker Help us to close this question.. :))

网友:这本书Rubyist题材涵盖自我我认为很好。

(原文:The book The Well-Grounded Rubyist covers self quite well I think.)

网友:问:之前你需要做更多的研究meta.stackoverflow.com/questions/261592/?,catb.org/esr/faqs/smart-questions.html。

(原文:You need to do more research before asking: meta.stackoverflow.com/questions/261592/…, and catb.org/esr/faqs/smart-questions.html.)

解决方案:
目前在上下文中指的对象。在你的例子中,自我本身,并定义一个类方法。例如:您也可以使用自己在一个类的实例。在这种情况下,自我是指的实例。有一个很好的博客在自我在Ruby中,或者,在评论中指出,有一些在这个Ruby文档。
原文:

self refers to the object that is currently in context.

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"

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!"

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

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.