Singleton method vs. class method

后端 未结 5 835
一向
一向 2021-02-08 16:31

Are class method and singleton method doing the same or different? Here is an example.

class C
  def self.classmethod
    puts \"class method #{self}\"
  end
end         


        
5条回答
  •  礼貌的吻别
    2021-02-08 16:46

    Most of what happens in Ruby involves classes and modules, containing definitions of instance methods

    class C
      def talk
        puts "Hi!"
      end
    end
    
    c = C.new
    c.talk
    Output: Hi!
    

    But as you saw earlier (even earlier than you saw instance methods inside classes), you can also define singleton methods directly on individual objects:

    obj = Object.new
    def obj.talk
      puts "Hi!"
    end
    obj.talk
    #Output: Hi!
    

    When you define a singleton method on a given object, only that object can call that method. As you’ve seen, the most common type of singleton method is the class method—a method added to a Class object on an individual basis:

    class Car
      def self.makes
        %w{ Honda Ford Toyota Chevrolet Volvo }
      end
    end
    

    But any object can have singleton methods added to it. The ability to define method- driven behavior on a per-object basis is one of the hallmarks of Ruby’s design.

    Singleton classes

    Singleton classes are anonymous: although they’re class objects (instances of the class Class ), they spring up automatically without being given a name. Nonetheless, you can open the class-definition body of a singleton class and add instance methods, class methods, and constants to it, as you would with a regular class.

    Note:

    Every object has two classes:

    ■ The class of which it’s an instance

    ■ Its singleton class

    ----------------------------------------------------------------

    At Last I would highly recommends you to watch.

    1: The Ruby Object Model and Metaprogramming For detail info about singleton method vs. class method ruby

    2: MetaProgramming - Extending Ruby for Fun and Profit - by Dave Thomas

    Hope this help you!!!

提交回复
热议问题