以前在讲多态的时候总喜欢举父亲打孩子的例子,今天写了一个Ruby版,稍后献上Ruby语法速查
class Father
attr_accessor :name
def initialize(name)
@name =
name
end
def beat(child)
child.beaten
end
end
class Son < Father
def beaten
puts @name +
" is running away while father beat him";
end
end
class Daughter < Father
def beaten
puts @name +
" is crying while father beat her";
end
end
father = Father.new('Father')
son = Son.new('Son')
daughter = Daughter.new('Daughter')
father.beat(son)
father.beat(daughter)
文章来源:
http://blog.sina.com.cn/u/4a5ca02401000761