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,也会自动返回表达式的值。