讓我們來定義一個類,類名是Person,類名首字母要大寫;屬性有姓名@name、年齡@age、國籍@motherland,實例變量用@開頭; 方法有一個,叫talk, 方法名和參數名應該用一個小寫字母開頭或者用一個下劃線開頭,看程序 E4.3-1.rb 。#=>my name is kaichuan, age is 20
I am a Chinese.
my name is Ben, age is 18
I am a foreigner.
@age.to_s的含義是:將數@age轉換爲字符串。
initialize是初始化方法,相當於Java的構造器。參數age有一個缺省值18,可以在任何方法內使用缺省參數,而不僅僅是initialize。如果有缺省參數,參數表必須以有缺省值的參數結尾。
- class Person
- def initialize( name, age=18 )
- @name = name
- @age = age
- @motherland = "China"
- end #初始化方法結束
- def talk
- puts "my name is "+@name+", age is "+@age.to_s
- if @motherland == "China"
- puts "I am a Chinese."
- else
- puts "I am a foreigner."
- end
- end # talk方法結束
- attr_writer :motherland
- end # Person類結束
- p1=Person.new("kaichuan",20)
- p1.talk
- p2=Person.new("Ben")
- p2.motherland="ABC"
- p2.talk
attr_writer :motherland 相當於
def motherland=(value)
return @motherland =value
end
|
attr_ reader :motherland 相當於
def motherland
return @motherland
end
|
這就是我們熟悉的getter 和setter 方法的簡寫形式。你不熟悉也不重要。
attr_accessor :motherland 相當於attr_reader:motherland; attr_writer :motherland
這個Person類可以talk,如何實現的?寫Person類的人知道,其它的類不知道,只是調用而已。封裝完成了隱藏實現。
完整閱讀,請看我寫的 Ruby語言中文教程all in one