1.
class Person
def initialize
puts "nijhao"
end
def talk (name)
puts "your name is #{name} "
end
end
=begin
p = Person.new
p.talk("samba")
=end
class Student < Person
def talk (name)
super
puts "your name is #{name}"
end
end
p1 = Person.new
p1.talk("gjhohj")
p2 = Student.new
p2.talk("samba")
2.
#实例变量、类变量、类方法
#与全局变量和实例变量不同,类变量在使用前必须要初始化;全局变量和实例变量如果没有初始化,其值为 nil 。
class Student
@@count = 0 ; #类变量
def initialize(name)
@name = name
@@count += 1
end
def talk
puts "name= #@name,this is class count #@@count"
end
end
p = Student.new("samba")
p1 = Student.new("gjhohj")
p1.talk
p.talk
3.
#static class
class Student
@@count = 0
def initialize
@@count += 1
end
def Student.classCount
puts "class's count #@@count"
end
end
p = Student.new
p1 = Student.new
Student.classCount
4.
#实例方法
class Person
def talk
puts "hello"
end
end
p1 = Person.new
p2 = Person.new
def p2.talk
puts "ps hello"
end
def p2.laugh
puts "he he he!!!!"
end
p1.talk
p2.talk
p2.laugh