類定義
class Song
def initialize(parameters) # constructor
@name = . # instance field variable
end
end
object.inspect # 查看一個實例的內部信息
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其實就是一個類方法, ClassName.new
Singleton類
class Singleton
private_class_method :new # 重定義constructor的可見度為private
@@singleton = nil # 初始化一個Class變量
def create
@@singleton = new unless @@singleton # new一個,除非@@singleton不為nil
@@singleton # 不能省略,雖然@@singleton = new會返回@@singleton,但是第二次調用create時,
# @@singleton = new并不執行
end
end
private可見度
只能是當前實例,即self,即使是同一類的其他實例也不可以(這和其他大多數的面向對象語言不同)
比如f是F類的一個private方法
class F
def test()
obj = F.new
obj.f # 這在ruby中是不行的, 但是只有test被調用時,才會有NoMethodError
f # 沒有問題,這是self.f
end
end
變量
person = "Tim"
person.object_id => person的id
person.class => person的類,即String
person.dup => Clone一個實例
person.freeze => 凍住,不能再修改
轉載請保留
http://www.tkk7.com/xilaile/archive/2007/05/06/115603.html