#单例方法:对象的实例方法,其只属于具体类实例对象
#实例方法,属于类的每个实例对象。单例方法只出现在单个实例对象中
class Person
def talk
puts "This is a Person class."
end
end
p1=Person.new
p2=Person.new
#定义单例方法,首先要生成一个实例对象,其次,要在方法名前加上对象名和一个点号“.”
def p2.talk
puts "This talk method belongs to p2."
end
def p2.laugh
puts "laugh method belongs to p2."
end
p1.talk #This is a Person class.
p2.talk #This talk method belongs to p2.
p2.laugh #laugh method belongs to p2.
def talk
puts "This is a Person class."
end
end
p1=Person.new
p2=Person.new
#定义单例方法,首先要生成一个实例对象,其次,要在方法名前加上对象名和一个点号“.”
def p2.talk
puts "This talk method belongs to p2."
end
def p2.laugh
puts "laugh method belongs to p2."
end
p1.talk #This is a Person class.
p2.talk #This talk method belongs to p2.
p2.laugh #laugh method belongs to p2.