1.module
ruby 代码
- #模块 module
- #语法 module......end
- #Mix-in:通过Module实现了类似多重继承的功能
- module Me
- def sqrt(num)
- num*=10
- end
- end
- class Person
- def talk
- puts "I'am talking"
- end
- end
- class Student < Person
- include Me
- end
- student = Student.new
- student.talk
- puts student.sqrt(10)
- #与include 方法相对应,还有一个extend方法
- #如果并不是Student的每个对象都会求平方根,只有一个学生会,就需要用到extends
- class StudentTest
- end
- aStudent = StudentTest.new
- aStudent.extend(Me)
- puts aStudent.sqrt(9)
- #说明 :include方法为一个类的所有对象包含某个module,extend为某个类的某一个对象包含某个module
运行结果:
I'am talking
100
90
1568

被折叠的 条评论
为什么被折叠?



