且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ruby的模块和包含其他模块

更新时间:2021-09-16 18:44:24

ruby中有类似vb的模块module

如:

module Summable

  def sum

    inject {|v,n| v+n}

  end

end

 

class Array

  include Summable

end

 

class Range

  include Summable

end

 

class VowelFinder

  include Summable

end

 

[1,2,3,4,5].sum  得到 15

('a'..'m')  得到 "abcdefghijklm"

vf=VowelFinder.new("the quick brown fox jumped")

vf.sum  得到 "euiooue"

 

在一个ruby文件中引用另一个的用法

如:

included.rb为

a=1

def b

  2

end

 

放到另一个文件

a="cat"

b="dog"

require 'included'

a 得到  "cat"

b 得到  "dog"

b()  得到 2

 

注:require也可以改为 load