Ruby extend | include

extend 扩展

先来看两段代码

module Mod
  def hello
    puts 'hello for module Mod'
  end
end

class Klass  
  def hello
    puts 'hello for class klass'
  end
end

k = Klass.new
k.hello                         #hello for class klass
puts k                          #
k.extend(Mod)
k.hello                         #hello for module Mod
puts k                          #
module Mod
  def hello
    puts 'hello for module Mod'
  end
end

class Klass
  self.extend Mod
  
  def hello
    puts 'hello for class klass'
  end
end


k = Klass.new       
k.hello                          #hello for class klass
Klass.hello                      #hello for module Mod
  • extend 是针对object的扩展(因为class本身也是一个object)或者说是 类方法?
  • extend 插入的祖先链低于object的class 所以Mod里面的hello被先调用

include 带入

#!/usr/bin/env ruby

module Mod
  def hello
    puts 'Mod\'s hello'
  end
  
  class << self
    def included(base)
      def base.call
        puts 'base call'
      end
      
      base.extend ClassMethods
    end
  end
  
  module ClassMethods
    def hi
      puts 'hi'
    end
  end
end


class Test
  include Mod
end

Test.hi                    #hi
Test.call                  #base call
Test.new.hello             #Mod's hello
  • 针对那个extend。 可以说include 一般是被 class 用的 实例方法?

  • 最后ruby2.0开始引入prepend 作用类似于include 只不过祖先链处于接收者本身下面

module M
  
  def test_method
    puts 'this is test'
  end
  
  def anthor_method
    puts 'anthor_method'
  end
  
end

class C
  include M
end

class AnotherC
  extend M
end

C.new.test_method #this is test
AnotherC.anthor_method #anthor_method

Over

你可能感兴趣的:(Ruby extend | include)