扩展类
继承
class Parent
def hello
p "Hello Ruby"
end
end
class Child < Parent
end
=begin
Child = Class.new(Parent)
等价于上面定义继承类的办法
=end
child = Child.new
child.hello
class Parent
def hello
p "Hello Ruby"
end
end
class Child < Parent
def hello
p "你好, Ruby"
end
end
child = Child.new
child.hello
#=> "你好, Ruby" 父类的方法被覆盖了
class Parent
def hello
p "Hello Ruby"
end
end
class Child < Parent
def hello
#super相当于php的parent::
super
p "你好, Ruby"
end
end
child = Child.new
child.hello
#=> "Hello Ruby"
#=> "你好, Ruby"
alias与undef
alias
# coding: utf-8
class Parent
def hello
p "Hello Ruby"
end
end
class Child < Parent
#给父类的方法定义别名,这样就不会和子类方法冲突了
alias parent_hello hello
#使用符号也是可以的,随意~
#alias :parent_hello :hello
def hello
p "你好, Ruby"
end
end
child = Child.new
child.hello
#=> "你好, Ruby"
child.parent_hello
#=> "Hello Ruby"
undef
# coding: utf-8
class Parent
def hello
p "Hello Ruby"
end
end
class Child < Parent
undef hello
#undef hello
end
child = Child.new
child.hello
#=> 报错,因为hello方法已经被删除了
单例类
str1 = "Ruby"
str2 = "Ruby"
=begin
Ruby中,所有类都是class类的实例
给class类添加实例方法
=end
class << str1
def hello
"Hello, #{self}!"
end
end
p str1.hello
#=> 成功
p str2.hello
#=> 报错,str2没有hello这个方法