文章目錄
ruby的類
首字母大寫,執行個體變數名以@開頭,方法名和參數名用小寫字母或_開頭。
class Person
def initialize(name)
@name = name
@motherland = "china"
end
def talk
puts "my name is " + @name
puts "my motherland is " + @motherland
end
end
talk函數因為沒有參數,所以可以省略括弧。
getter和setter函數可以定義為(以@motherland為例):
def motherland
return @motherland
end
def motherland = (m)
@motherland = m
end
也可以簡寫為attr_reader:motherland和attr_writer:mother,更簡單的話可以寫為attr_accessor:motherland,這一句話把getter和setter都包括了。
使用這個類的方式如下:
p = Person.new("meteor")
puts p.motherland
p.motherland = "england"
p.talk
類的繼承
使用<符號表示繼承
class Student < Person
def talk
puts "students, name: " + @name;
super.talk;
end
end
調用父類的方法用super指明。
所有類的最終父類是Object類,Object類定義了new, initialize...方法。
多態
ruby的函數不能重載。ruby的所有函數相對於C++來說都是virtual的,好像除了C++之外,其它語言都是這樣的。
動態語言
ruby是動態語言,ruby中的類定義之後可以再次定義,重新定義的時候可以往裡增加新的方法,修改原先的方法,增加新的變數等,甚至可以刪除方法。
class Student
undef talk
end
可以undef的有方法、局部變數、常量,不能undef類、執行個體變數。
另外,remove_method會remove掉當前的方法定義,undef_method會remove掉所有方法的定義。
remove_const可以remove掉常量或者類。
編碼
ruby中,有時將"!"或"?"附於方法名後,"!"表示這個方法具有破壞性,有可能改變傳入的參數,"?"表示這是一個布爾方法,只會返回true或false。
ruby中經常可以省略小括弧
ruby的函數中如果有return語句,會在return處返回,可能會返回一個值,如果最後一行是運算式,那麼即使不寫return,也會自動返回運算式的值。