让我们来定义一个类,类名是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。如果有缺省参数,参数表必须以有缺省值的参数结尾。
ruby 代码
- 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