Ruby self keyword

孤人 提交于 2019-12-20 15:26:23

问题


im having trouble understanding the self keyword . I get how it's used to distinguish between Instance Methods and Class Methods but what about when it's used from inside a method.

Something like

def self.name
 self.name = "TEXT"
end

or

def name2
 self.name = "TEXT2"
end

or

class Array
 def iterate!(&code)
  self.each_with_index do |n, i|
   self[i] = code.call(n)
  end
 end
end

回答1:


Usually, self as a receiver can be omitted, and in such cases, it is usually preferable to do so. However, there are a few cases when omitting self make the code mean something else.

  • One such case is, as in your example self.name = ..., using a setter method. Ruby's syntax is ambiguous between method and variable call, and when something that can be interpreted either as a variable or a method is followed by =, its interpretation as a local variable assignment has priority.

  • Another case is when you want to call the method class. There is also the keyword class, and interpretation of class as the keyword has priority over it as the method.

  • Still another case is when you want to use the method []. This notation is also used for array literal, and interpretation of it as an array has priority over it as a method.

In each of these cases, you have to make the expression be unamgiguously a method call. One way is to explicitly write the receiver even when it is self. The other way is to write () after the method.

Regarding your example self.each_with_index ..., the self can be omitted, and not doing so is not a recommended practice.




回答2:


self has absolutely nothing whatsoever to do with the difference between instance methods and class methods. In fact, there isn't even a difference between them, because Ruby doesn't have class methods. Ruby only has instance methods.

self in Ruby is exactly the same as self (or sometimes called this) in every other object-oriented language: it is a reference to the current object. That's all it is. It literally is just a pointer to "myself".




回答3:


self actually defines your scope in Ruby . Scope keeps changing when you switches from module to class, class to method and so on....




回答4:


Class method (because self references to the class):

class MyClass
  def self.myMethod
    "hello"
  end
end

MyClass.myMethod

Whereas a method without self is an instance method:

class MyClass
  def myMethod
    "hello"
  end
end

c = MyClass.new
c.hello

For variables, it also is a scope thing. If your class has an accessor, you access it with self. Not using self would usually mean that you want to access a local variable from your method's scope (assuming no magic is given).

class MyClass
  attr_accessor :var

  def myMethod
    self.var # => "hello"
    var # => undefined
  end
end


来源:https://stackoverflow.com/questions/15297161/ruby-self-keyword

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