Ruby Mix-in 和 Extend 终于有点清晰了

saxer · March 28, 2015 · Last by saxer replied at March 28, 2015 · 3128 hits

Mix-in

这里提到的 mix-in 是指使用 include 使类包含模块

moudle M
      def meth
          "meth"
      end
 end
 class C
      include M #包含模块
 end
 c = C.new
 p c.meth     #=>     meth

判断某个类是否包含某个模块,可以使用 include?方法

C.include?(M)     #=>    true

祖先和父类

p C.ancestors          #=>     [C, M, Object, Kernel, BasicObject]
p C.superclass         #=>     Object

因此,C 引入模块,那么相应的模块也将会被认为是 C 的祖先 (ancestors),而 superclass 会直接返回 C 类的直接父类

Kernel Kernel 是 ruby 内部的一个核心模块,Ruby 程序运行时所需的共通函数都封装在次模块中,例:p 方法、raise 方法等都是由 Kernel 提供的模块函数

使用 Mix-in 时方法的查找顺序 • 一个类中包含多个模块时,优先使用最后一个包含的模块。 • 相同的模块被包含两次 (含两次) 以上时,第二次以后的会被忽略。

Extend 与 Include 例:使用 extend 给类追加类方法,使用 Include 给类追加实例方法

moudle ClassMethods
     def cmethod
          "class method"
     end
end
moudle InstanceMethods 
     def imethod
          "instance method"
     end
end
Class MyClass
   extend ClassMethods
   include InstanceMethods
end

p MyClass.cmethod          #=>     “Class method"
p MyClass.new.imethod     #=>     “instance method"

定义类方法

class HelloWord
end

我们想给 Helloword 定义类方法,有以下几种选择

class << HelloWord
     def hello(name)
          puts "#{name} said hello."
     end
end
class HelloWord

     class << self
          def hello(name)
               puts "#{name} said hello."
          end
     end

     def HelloWord.hello2(name)
          puts "#{name}2 said hello."
     end 

     def self.hello2(name)
          puts "#{name}3 said hello."
     end 

end

extend 就相当于在类的 meta class 里 include,这样的东西你看看 Ruby 元编程那本书就全懂了,那真是本神奇的书。

You need to Sign in before reply, if you don't have an account, please Sign up first.