1、类名的定义以大写字母开头,单词首字母大写,不用"_"分隔
2、实例化对象的时候调用new方法,实际上调用的是类里边的initialize方法,是ruby类的初始化方法,功能等同于Java中的构造方法
- class Person
- def initialize(name, gender, age)
- @name = name
- @gender = gender
- @age = age
- end
- end
- class Person
- attr_accessor :name, :gender, :age
- end
- class Person
- def name
- @name
- end
- def name=(name)
- @name=name
- end
- def gender
- @gender
- end
- def gender=(gender)
- @gender=gender
- end
- def age
- @age
- end
- def age=(age)
- @age=age
- end
- end
4、Ruby中没有接口,但是有更神奇的Module和Mix-in机制,注意:module中的静态方法只能通过模块名访问,实例方法只能通过include到类中,然后通过类的实例访问。
- module Foo
- PI = 3.14
- def m1
- puts 'Put out from m1!'
- end
- def Foo.m2
- puts 'Put out from m2!'
- end
- class Fooc
- def mfc
- puts 'Put out from Foo>>Fooc!'
- end
- end
- module Foos
- def mfs
- puts 'Put out from Foo>>Foos'
- end
- end
- end
- #通过module名访问,只能访问类一级的内容
- puts Foo::PI.to_s #输出:3.14
- Foo::Fooc.new.mfc #输出:Put out from Foo>>Fooc!!
- #Foo.m1 #无法访问,没有实例化
- Foo.m2 #静态方法通过模块名访问
- #引入后访问
- include Foo
- m1 #输出:Put out from m1!
- Fooc.new.mfc #输出:Put out from Foo>>Fooc!!
- include Foos
- mfs #输出:Put out from Foo>>Foos!
- #鸭子类
- class Duck
- def swim
- print self.class , " can swim...\n";
- end
- end
- #"会飞的"模块
- module FlyModule
- def fly
- print " and I can fly...\n"
- end
- end
- #野鸭(会飞,会游)
- class Mallard < Duck
- include FlyModule #导入模块后,该类即具有模块中定义的方法(可以理解为实现了接口)
- end
- #家鸭(只会游泳)
- class Coot < Duck
- end
- m = Mallard.new
- m.swim
- m.fly
- c1 = Coot.new
- c1.swim
- #c1.fly #无法调用,报错提示未定义
- #module中定义的方法也可以在实例中动态扩展
- c2 = Coot.new
- c2.extend(FlyModule) #扩展c2对象引入FlyModule模块
- c2.swim
- c2.fly