定义模块用module...end 。模块与类非常相似,但是:
模块不可以有实例对象;
模块不可以有子类。
#Module(模块)
module Module1
def sqrt(num, rx=1, e=1e-10)
num*=1.0
(num - rx*rx).abs <e ? rx : sqrt(num, (num/rx + rx)/2, e)
end
end
puts "Module demo:"
include Module1
puts sqrt(456, 7, 0.01) #21.3541565188558
module Module1
def sqrt(num, rx=1, e=1e-10)
num*=1.0
(num - rx*rx).abs <e ? rx : sqrt(num, (num/rx + rx)/2, e)
end
end
puts "Module demo:"
include Module1
puts sqrt(456, 7, 0.01) #21.3541565188558
#Module(模块)方法;模块方法提供了一个途径,在模块的外部访问模块内部方法,无须 include 模块。定义模块常量不需要如此。
module Module2
def Module2.sayHello(*num)
"Welcome to Ruby world."
end
PI=3.14
end
puts "Module method:"
puts Module2.sayHello
puts Module2::PI #3.14
puts Math::PI #3.141592653589793
def Module2.sayHello(*num)
"Welcome to Ruby world."
end
PI=3.14
end
puts "Module method:"
puts Module2.sayHello
puts Module2::PI #3.14
puts Math::PI #3.141592653589793
#模块的第三个作用:实现了类似多重继承的功能
puts "multiple inheritance:"
class Person
def talk
puts "I'm talking."
end
#通过"include 模块名 " ,一个类可以得到某个模块的常量和方法,这里为了演示多继承,我们把其放到子类
#include Module1
end
=begin
person=Person.new
person.talk # I'm talking.
puts person.sqrt(20.7,3.3) # 4.54972526643248
=end
class Student < Person
#通过"include 模块名 " ,一个类可以得到某个模块的常量和方法
include Module1
end
aStudent=Student.new
aStudent.talk # I'm talking.
puts aStudent.sqrt(20.7,3.3) # 4.54972526643248
class Person
def talk
puts "I'm talking."
end
#通过"include 模块名 " ,一个类可以得到某个模块的常量和方法,这里为了演示多继承,我们把其放到子类
#include Module1
end
=begin
person=Person.new
person.talk # I'm talking.
puts person.sqrt(20.7,3.3) # 4.54972526643248
=end
class Student < Person
#通过"include 模块名 " ,一个类可以得到某个模块的常量和方法
include Module1
end
aStudent=Student.new
aStudent.talk # I'm talking.
puts aStudent.sqrt(20.7,3.3) # 4.54972526643248
#extend:给特定对象实例添加Module
class StudentEx
end
stuEx=StudentEx.new
stuEx.extend(Module1)
puts stuEx.sqrt(20.7,3.3) # 4.54972526643248
end
stuEx=StudentEx.new
stuEx.extend(Module1)
puts stuEx.sqrt(20.7,3.3) # 4.54972526643248