先看一段代码,引用自runoob
module Moral
VERY_BAD = 0
BAD = 1
def Moral.sin(badness)
# ...
end
end
这里说一下Ruby的类方法的写法, 其实我更倾向于下面这样的写法
module Moral
VERY_BAD = 0
BAD = 1
# ... 看这里
def self.sin(badness)
# ...
end
end
因为我在写示例的时间遇到了一个问题
require': cannot load such file -- *** (LoadError)
因为我第一个样例是把module和 class放在一个 .rb文件所以没有遇到这个问题,
module Trig
PI = 3.1415926
def sin(x)
puts 'Trig 的 sin 方法'
end
def self.cos(x)
puts 'Trig 的 cos 方法'
end
end
class UMath
include Trig
end
UMath.new.sin(1)
这样便可以调用sin方法,如果定义了类方法的话,就要换一种调用方式了.
Trig.cos(2)
但是如果跨文件的话 ,假如module: Moral 在moral.rb文件中, 那就要这样写了.
$LOAD_PATH << '.'
require 'moral'
# require_relative 'moral' # 这样写等价与上面两行,相对路径与绝对路径?
y = Moral.sin('2')
***
mixin 与 多继承module A
def a1
end
def a2
end
end
module B
def b1
end
def b2
end
end
class Sample
include A
include B
def s1
end
end
samp=Sample.new
samp.a1
samp.a2
samp.b1
samp.b2
samp.s1