1、類名的定義以大寫字母開頭,單詞首字母大寫,不用"_"分隔
2、實例化對象的時候調用new方法,實際上調用的是類裏邊的initialize方法,是ruby類的初始化方法,功能等同於Java中的構造方法
class Person
def initialize(name, gender, age)
@name = name
@gender = gender
@age = age
end
end
3、可以使用attr_accessor關鍵字標記實例變量,爲其提供讀寫方法,類似java中的get&set方法,如定義個最簡單的model對象:
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
可見,使用了attr_accessor關鍵字,可以使代碼更簡潔易懂,此外,ruby中還提供讀寫分開的關鍵字:attr_writer(只寫)、attr_reader(只讀)。
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!
可以來看看Module在實在應用中是怎麼使用的:
#鴨子類
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