#一、定义一个类
class Person
def initialize(name,age=18)
@name=name;
@age=age;
@motherland="china";
end
def talk
puts "my name is "+@name+" and I am "+@age.to_s
if @motherland == "china"
puts "I am a Chinese."
else
puts "I am a foreigner."
end
end#talk结束
attr_writer:motherland
attr_writer:age
end#class结束
p1=Person.new("Zhangren",10);
p1.talk;
p1.motherland="abc";
p1.talk;
p1.age=20;
p1.talk;
#二、继承自一个类
class Student < Person
def talk
#super;#这会调用父类talk中的代码
puts "I am a student. my name is "+@name+", age is "+@age.to_s
end # talk方法结束
end # Student类结束
p3=Student.new("kaichuan",25); p3.talk
p4=Student.new("Ben"); p4.talk
#Ruby没有重载方法,因为参数没有类型,所以没法重载。有多态,不过不太明显,因为变量都没有类型,所以谈不上父类引用指向子类对象,都是统一的引用。
#三、变量动态性
# E5.3-1.rb
a=5
b="hh"
puts "a = #{a} #{b} #{a}"
puts "b = #{b}"
#四、重写
def talk (a,b=1)
puts "This is talk version 2."
end
def talk (a)
puts "This is talk version 1."
end
talk (2) # This is talk version 1.
#talk (2,7) # 报错,因为重写之后,只有后一个有用,没有重载。父子类中也是重写。
#五、Ruby的变量等标识名称区分太小写。全局变量用$引用,实例变量用@(也就是成员变量,因为不需要声明,都是直接用),类变量用@@(其实就相当于静态变量)
$a="/n a is a global value"
puts $a
class StudentClass
@@count=0
def initialize( name )
@name = name
@@count+=1
end
def talk
puts "I am #@name, This class have #@@count students."
end
end
p1=StudentClass.new("Student 1 ")
p2=StudentClass.new("Student 2 ")
p3=StudentClass.new("Student 3 ")
p3.talk # I am Student 3 , This class have 3 students.
p4=StudentClass.new("Student 4 ")
p4.talk # I am Student 4 , This class have 4 students.
#六、定义类方法(即静态方法)
class StudentClass
@@count=0
def initialize
@@count+=1
end
def StudentClass.student_count#定义时需要类名加方法名,与一般方法不同,与Java的static修饰也不一样。没有参数就不需要括号
puts "This class have #@@count students."
end
end
p1=StudentClass.new
p2=StudentClass.new
StudentClass.student_count # This class have 2 students.调用时,用类名加方法名即可。
p3=StudentClass.new
p4=StudentClass.new
StudentClass.student_count # This class have 4 students.
#七、实例的方法添加—单例方法,即给某一实例添加方法。一般只使用一次。不知道用途如何,呵呵。
#E6.4-1.rb
class PersonTwo
def talk
puts "Hi! "
end
end
p1=PersonTwo.new
p2=PersonTwo.new
def p2.talk #定义单例方法p2.talk
puts "Here is p2. "
end
def p2.laugh #定义单例方法p2. laugh
puts "ha,ha,ha... "
end
p1.talk # Hello!
p2.talk # Here is p2.
p2.laugh # ha,ha,ha...
#八、访问控制
#在Ruby里,要读取,或是改变对象的属性,唯一的途径是调用对象的方法。控制了对方法的访问,也就控制了对对象属性的访问。也即访问控制只针对方法。属性都是private的。
#控制对方法的访问,有三种方式:
#public方法,可以被定义它的类和其子类访问,可以被类和子类的实例对象调用;
#protected方法,可以被定义它的类和其子类访问,不能被类和子类的实例对象直接调用,但是可以在类和子类中指定给实例对象,也即指在类中写另一方法调用protected方法,该另一方法接受一个实例变量作为参数;
#private方法,可以被定义它的类和其子类访问,私有方法不能指定对象。
class PersonThree
def speak
"protected:speak "
end
def laugh
" private:laugh"
end
protected :speak#以这种方法指明访问控制符号
private :laugh
def useLaugh(another)
puts another.laugh #这里错误,私有方法不能指定对象
end
def useSpeak(another)
puts another.speak
end
end
p1=PersonThree.new
p2=PersonThree.new
p2.useSpeak(p1) # protected:speak
#p2.useLaugh(p1)