Ruby學(xué)習(xí)筆記2,第三章
類定義
class Song
def initialize(parameters) # constructor
@name = . # instance field variable
end
end
object.inspect # 查看一個(gè)實(shí)例的內(nèi)部信息
object.to_s # Java Object.toString()
繼承
class KaraokeSong < Song # < 表示繼承
end
Getter
attr_reader :name, :artist
Setter
def name= name
@name = name
end
song.name = newName
attr_writer :name
類變量
@@class_var = .
類方法
def Class.method
constructor其實(shí)就是一個(gè)類方法, ClassName.new
Singleton類
class Singleton
private_class_method :new # 重定義constructor的可見度為private
@@singleton = nil # 初始化一個(gè)Class變量
def create
@@singleton = new unless @@singleton # new一個(gè),除非@@singleton不為nil
@@singleton # 不能省略,雖然@@singleton = new會(huì)返回@@singleton,但是第二次調(diào)用create時(shí),
# @@singleton = new并不執(zhí)行
end
end
private可見度
只能是當(dāng)前實(shí)例,即self,即使是同一類的其他實(shí)例也不可以(這和其他大多數(shù)的面向?qū)ο笳Z言不同)
比如f是F類的一個(gè)private方法
class F
def test()
obj = F.new
obj.f # 這在ruby中是不行的, 但是只有test被調(diào)用時(shí),才會(huì)有NoMethodError
f # 沒有問題,這是self.f
end
end
變量
person = "Tim"
person.object_id => person的id
person.class => person的類,即String
person.dup => Clone一個(gè)實(shí)例
person.freeze => 凍住,不能再修改
轉(zhuǎn)載請保留http://www.aygfsteel.com/xilaile/archive/2007/05/06/115603.html