论坛首页 编程语言技术论坛

从 include 看ruby的实现方式

浏览 1889 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-02-26  
class Dog
  def include_mod # not workable
    include Mod
  end
 
  def self.include_mod #workable
    include Mod
  end
end

module Mod
  def shat
    puts "shat"
  end
end

dog = Dog.new
dog.class.include_mod
puts Dog.instance_method :shat
dog.include_mod

#'include' is a method belonging to Module
#Class inherit Module, so Class can include
#And 'include' is one of Module's instance methods, so the decleared module Mod has a method include.
#Module is Class, and Class is a Module. Both of them has two set of methods: instance_methods and his owner methods.
instance method 'include' in Class is passed into Dog as regular method when declaration.
but when declear "dog = Dog.new", 'include' is not a instance method any more in Dog. So dog can't include.
   发表时间:2009-02-27  
include予class instance methods
extend予class class methods
0 请登录后投票
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics