(九)模块
(1)模块的使用
把一堆方法和常量放在一起就是模块,比如Math模块就是包含一堆数学运算的方法和常量
如下模块通过类名就能调用了,你要是无聊也可以用::去调用模块方法
模块通过类名就能调用,类方法也是通过类名就能调用,那么模块方法和类方法有什么区别呢?=》模块没有实例,模块方法没有new方法
puts Math::PI
puts
Math.sqrt(25)
puts
Math::sqrt(9)
Math.new
模块(Module)不仅没有实例,也不能被继承
(2)自定义模块
module Test
PII=3.141
PII=3.141
def sqrt(number)
Math.sqrt(number)
end
end
puts Test::PII
puts Test::sqrt(9)
def sqrt(number)
Math.sqrt(number)
end
end
puts Test::PII
puts Test::sqrt(9)
模块没有实例,所以只能有类方法,正确写法如下:
module Test
PII=3.141
def self.sqrt(number)
Math.sqrt(number)
end
end
puts Test::PII
puts Test::sqrt(9)
puts Test::sqrt(25)
模块没有实例就不能调用实例方法了吗?=》不是
可以让一个类include模块,这样该类就获得了模块的实例方法(常量和类方法还是不能用)
module Test
PII=3.141
def self.sqrt(number)
Math.sqrt(number)
end
def hello
puts "hello world"
end
end
class Student
include Test
def initialize(no)
@no=no
end
end
a=Student.new(10)
a.hello
a.PII
Student.sqrt