ruby

领取游戏新手卡来http://5433.com

导航

Ruby动态追加类定义

Ruby是动态语言,允许随时更改类定义,如我们在定义一个类时,该类已经存在,则此时的定义是对先前类的追加,而不是重新定义.

 

class Apple
  def show
    puts 
"一个苹果"
  end
end
a
=Apple.new()
a.show

class Apple
  #为Apple类追加一个test方法
  def test
    puts 
"口感不错"
  end
end

a
=Apple.new()
a.show
a.test

 

使用特殊类定义为某个对像追加方法和变量.

 

class << a
  def name
    puts 
"富士"
  end
end

a.show
a.name

 

 

使用特殊类定义为a对象追加了个name方法后,a就可以调用name方法,但其它的Apple实例依然没有name方法.

posted on 2010-03-08 11:45  最初的模样  阅读(443)  评论(0编辑  收藏  举报