
正文
ruby 中的 module
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
Module是Class的父类:
>> Class.superclass
=> Modulemodule 没有实例变量
module 没有new不能生成实例对象
module内可以有常量
>> module Test
>> PI=3.14
>> end
=> 3.14
>> Test.PI
>> Test::PI
=> 3.14
module的方法有两种,一种是module方法,这类方法可以直接调用。
>> module Test
>> def Test.test_method
>> puts "hello from module"
>> end
>> end
=> nil
>> Test::test_method
hello from module
=> nil
另一种是没有module名字的方法,这种方法不能直接调用,需要mixin到一个类中。
>> module Test
>> def hello
>> puts "hello"
>> end
>> end
=> nil
>> Test::hello
NoMethodError: undefined method `hello' for Test:Module
from (irb):23
把module的方法添加到类中有两种方法。
一种是include,方法会被添加到实例方法中。
一种是extend,方法会被添加到类方法中。
继续前面的module Test的例子
>> class Class1
>> include Test
>> end
=> Class1
>> Class1.new.hello
hello
=> nil
>> class Class2
>> extend Test
>> end
=> Class2
>> Class2.hello
hello
=> nil
module常用的一个hook/callback是included方法,这个方法在module被include到一个类中的时候会被调用。
>> module Test
>> def self.included(cls)
>> puts "including module in class #{cls.name}"
>> end
>> end
=> nil
>> class Class1
>> include Test
>> end
including module in class Class1
=> Class1





