先看一段代码,引用自runoob
module Moral VERY_BAD = 0 BAD = 1 def Moral.sin(badness) # ... endend这里说一下Ruby的类方法的写法, 其实我更倾向于下面这样的写法
module Moral VERY_BAD = 0 BAD = 1 # ... 看这里 def self.sin(badness) # ... endend因为我在写示例的时间遇到了一个问题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 方法' endendclass UMath include TrigendUMath.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 endendmodule B def b1 end def b2 endend class Sampleinclude Ainclude B def s1 endend samp=Sample.newsamp.a1samp.a2samp.b1samp.b2samp.s1
新闻热点
疑难解答