What does self mean in Ruby? [duplicate]

回眸只為那壹抹淺笑 提交于 2019-12-30 16:19:30

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/35117203/what-does-self-mean-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!