对ruby的namespaces一些理解分享下
主要用到的namespaces的关键词是 module , require ,load ,include
module 的作用是圈出一个命名空间理解起来还简单,对于require,load,include的理解,先看下下面的代码
#A.rb
module All
def self.a
print "a\n"
end
end
print "loading in the A.rb\n"
#B.rb
module All
def self.b
print "b\n"
end
end
#test.rb
require "A"
require "B"
require "A"
require "A"
load "A.rb"
load "A.rb"
All.a
All.b
结果是:
loading in the A.rb
loading in the A.rb
loading in the A.rb
a
b
require 对于被加载的文件只加载一次,所以第一个是loading in the A.rb 因为require起作用的之后虽然还有很多的require但是不在触发打印出来 loading in the A.rb ,后两行是 load "A.rb"触发的,每次出现就会将被加载文件从新加载一次。而include就是一个mixin