To use self. or not.. in Rails

后端 未结 6 555
长情又很酷
长情又很酷 2020-11-30 21:29

I\'ve been coding in Ruby for sometime now, but I don\'t understand when to use:

def self.METHOD_NAME
end

or just:

def METH         


        
6条回答
  •  旧时难觅i
    2020-11-30 22:24

    A quick explanation of what that means:

    In ruby, you can define methods on a particular object:

    a = "hello"
    
    def a.informal
      "hi"
    end
    
    a.informal
    => "hi"
    

    What happens when you do that is that the object a, which is of class String, gets its class changed to a "ghost" class, aka metaclass, singleton class or eigenclass. That new class superclass is String.

    Also, inside class definitions, self is set to the class being defined, so

    class Greeting
      def self.say_hello
        "Hello"
      end
      #is the same as:
      def Greeting.informal
        "hi"
      end
    end
    

    What happens there is that the object Greeting, which is of class Class, gets a new metaclass with the new methods, so when you call

    Greeting.informal
    => "hi"
    

    There's no such thing as class methods in ruby, but the semantics are similar.

提交回复
热议问题