sban : module of ruby

本文主要介绍ruby中module的使用方法。

模块在Ruby中起着极其重要的作用,其用module…end定义,定义与类类似。但与类不同的是:
一、模块不可以实例化。
二、模块不可以被继承。
模块其实是一些方法的集合。它的设计是要被其它类include,所以也不能被充许继承与实例化。

include用于在一个类中包括另一个模块定义的方法,而不需要重新定义。与ASP中的#include类似。
如果只是为该类的某一个对象包括特定的模块,也可以,用extend关键字。

module的功能在于三个:
一、功能相近相关的代码编在一个module中,便于基它类复用。Ruby其Mix-in的功能指模块可以内嵌于其它类中,实现的功能类似于C++的多继承,但比C++要简洁灵巧。但有一点,Mix-in以module为单位,不能单个Mix-in某module中的某方法。
二、Ruby中没有命名空间(namespace)一说,模块的名字便充当了这个角色。

在Flex SDK中,有一个文件mx.core.Version,这个文件不是类。如果自己写一个,也不要把它check进项目里,否则编译不过。若在Ruby写Version,则可以用module,如下:
文件:Version.rb:

module Version
VERSION = ‘0.1′; #常量声明也不需要const关键字。
end

如何使用一个module?很简单,如下:
文件Animal.rb:

require ‘Version’;

class Animal
include Version;

@name; #实例变量name

def initialize
@name = ‘animal’;
end

def bark
print “current version is “+VERSION+”\n”;
print “#@name is barking.\n” #在字符串中#变量以变量看待,这一点与php类似,但php不须额外加#
end
end

文件Cat.rb:

require ‘Animal’;

class Cat < Animal
def initialize
@name = 'cat';
end
end

Dog.rb:

require ‘Animal’;

class Dog < Animal
def initialize
@name = 'dog';
end
end

写个文件做一个测试,TestAnimal.rb:

require ‘Animal’;
require ‘Dog’;
require ‘Cat’;

$dog = Dog.new;
$cat = Cat.new;

$dog.bark;
$cat.bark;

include是对类而言,如果只是想使某一个对象($cat or $dog)具有VERSION属性,可以这样:

$cat.extend Version

当模块与类的定义不在同一个文件内时,需要使用require或者load。require与load的不同是:
一、require通常用于加载rb件,而load多用于加载配置文件。
二、对同一个文件,require只加载一次。load则会重复加载。
三、require加载文件时,可以省略文件后缀。而load不可以。

sban 2008/8/20于北京
原文链接:http://blog.sban.com.cn/2008/08/20/module-of-ruby.html

Related Posts

Last Modified

This entry was posted on 2008-08-20 and is filed under technique. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply