美文网首页
Ruby中类方法的定义

Ruby中类方法的定义

作者: Shawn_Wang | 来源:发表于2015-12-06 20:40 被阅读1416次

    Ruby中类方法的定义

    方法的接受者就是类本身(类对象)的方法成为类方法。类方法的几种形式如下:

    #1.在class <<类名 ~end 这个特殊的类定义中,以定义实例方法的形式来定义类方法
    class << HelloMethod
        def SayHello(name)
            puts "#{name} say hello"
        end
    end
    HelloMethod.SayHello("Bob")
    
    
    #2.在class上下文中使用self时,引用的对象是该类本身,因此可以使用class << self ~ end来定义
    
    class ClassMethod
      class << self
        def Hello(name)
          puts "#{name} say hello!"
        end
      end
    end
    ClassMethod.Hello("Bob")
    
    
    #3.使用def 类名.方法名 ~end 这样的形式来定义类方法
    class ClassMethod
        def ClassMethod.SayHello(name)
            puts "#{name} say hello"
        end
    end
    ClassMethod.SayHello("Ruby")
    
    #4.同样类似第二种方法一样使用self
    class ClassMethod
      def self.SayHello(name)
        puts "#{name} say hello"
      end
    end
    ClassMethod.SayHello("Bob")
    
    

    如果以为就是上面三种方法的话,那就大错特错了。上网查资料的时候发现还有下面这种方法: =。=

    class ClassMethod
        ClassMethod.instance_eval do
            def SayHello(name)
                puts "#{name} say hello"
            end
        end
    end
    

    使用extend关键字扩展类方法。

    module ClassMethod
      def cmethod
          "Class Method"
      end
    end
    class MyClass
      extend ClassMethod
    end
    p ClassMethod.cmethod #=>"Class Method"
    

    类方法定义:方法的接收者是类本身的方法成为类方法。在Ruby中,所有类本身都是Class类的对象,所以可以把类方法理解为:

    • Class类的实例方法
    • 类对象的单例方法

    相关文章

      网友评论

          本文标题:Ruby中类方法的定义

          本文链接:https://www.haomeiwen.com/subject/fvqehttx.html