Ruby Singleton methods for class and objects

后端 未结 3 391
别那么骄傲
别那么骄傲 2021-02-02 12:19

I am learning Ruby Singletons and i found some ways to define and get list of Class and Object singleton methods.

Class Singleton Methods

Ways to define

3条回答
  •  太阳男子
    2021-02-02 12:33

    Some more ways:

    Class singleton methods

    class << MyClass
      define_method :sixth_sing_method do
        puts "sixth"
      end
    end
    
    class MyClass
      class << self
        define_method :fourth_sing_method do
          puts "seventh"
        end
      end
    end
    

    Object singleton methods

    class << obj
      define_method :fourth_sing_method do
        puts "fourth"
      end
    end
    

    Next, you can use define_method and define_singleton_method in combination with send, e.g.

    obj.send :define_singleton_method, :nth_sing_method, lambda{ puts "nth" }
    

    and all possible combinations thereof. To use define_method, you need to capture the singleton class first as in this (the same works for class objects, too)

    singleton_class = class << obj; self end
    singleton_class.send :define_method, :nth_sing_method, lambda{ puts "nth" }
    

    Another ways is using class_eval on the singleton class objects:

    singleton_class.class_eval do
      def nth_sing_method
        puts "nth"
      end
    end
    

    And then you once again may combine send with class_eval...

    There are myriads of ways, I guess :)

提交回复
热议问题