What does def `self.function` name mean?

后端 未结 3 1707
轻奢々
轻奢々 2020-12-04 15:05

Can anyone explain to me what the meaning of adding self to the method definition is? Is it similar to the this keyword in java?

3条回答
  •  爱一瞬间的悲伤
    2020-12-04 15:48

    In ruby self is somewhat similar to this in java, but when it comes to classes its more like the keyword static in java. A short example:

    class A 
      # class method 
      def self.c_method
        true
      end
      # instance method
      def i_method
        true
      end
    end
    
    A.c_method #=> true
    A.i_method #=> failure
    A.new.i_method #=> true
    A.new.c_method #=> failure
    

    Update: Difference between static methods in java and class methods in ruby

    Static methods in Java have two distinct features that makes them different from instance methods: a) they are static, b) they are not associated with an instance. (IOW: they really aren't like methods at all, they are just procedures.) In Ruby, all methods are dynamic, and all methods are associated with an instance. In fact, unlike Java where there are three different kinds of "methods" (instance methods, static methods and constructors), there is only one kind of method in Ruby: instance methods. So, no: static methods in Java are completely unlike methods in Ruby. – Jörg W Mittag 1 hour ago

提交回复
热议问题