gr8vyguy@Blogjava

Ruby学习笔记2,第三章

类定义
  class Song
    def initialize(parameters)   # constructor
      @name = .                         # instance field variable
    end
  end
object.inspect      #  查看一个实例的内部信息
object.to_s           # Java Object.toString()

继承
  class KaraokeSong < Song     # < 表示继承
  end

Getter
  attr_reader :name, :artist

Setter
  def name= name
     @name = name
  end
song.name = newName

  attr_writer :name

类变量
  @@class_var = .

类方法
  def Class.method
  constructor其实就是一个类方法, ClassName.new

Singleton类
  class Singleton
    private_class_method :new   # 重定义constructor的可见度为private
    @@singleton = nil                   # 初始化一个Class变量

    def create
       @@singleton = new unless @@singleton      # new一个,除非@@singleton不为nil
       @@singleton    # 不能省略,虽然@@singleton = new会返回@@singleton,但是第二次调用create时,
                               # @@singleton = new并不执行
    end
  end

private可见度
  只能是当前实例,即self,即使是同一类的其他实例也不可以(这和其他大多数的面向对象语言不同)
  比如f是F类的一个private方法
  class F
     def test()
        obj = F.new
        obj.f   # 这在ruby中是不行的, 但是只有test被调用时,才会有NoMethodError
        f         # 没有问题,这是self.f
     end
  end

变量
  person = "Tim"
  person.object_id    => person的id
  person.class            => person的类,即String

  person.dup             => Clone一个实例
  person.freeze         => 冻住,不能再修改


转载请保留http://www.blogjava.net/xilaile/archive/2007/05/06/115603.html


posted on 2007-05-06 11:51 gr8vyguy 阅读(374) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 
<2007年5月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

导航

统计

公告

  • 转载请注明出处.
  • msn: gr8vyguy at live.com
  • 常用链接

    留言簿(9)

    随笔分类(68)

    随笔档案(80)

    文章分类(1)

    My Open Source Projects

    搜索

    积分与排名

    最新评论