Ruby学习笔记——类

类的定义:

1
2
3
4
5
6
7
class Song
  def initialize(name, artist, duration)
      @name = name        #实例变量
      @artist = artist
      @duration = duration
  end
end

在Ruby中,类永远都不是封闭的:你总可以向一个已有的类中添加方法。这个适用于你自己编写的类,同样适用于标准的内建(built-in)类。只要打开某个已有类的类定义,你就可以将指定的新内容添加进去,比如向上面已经定义的Song添加to_s方法:

1
2
3
4
5
class Song
  def to_s
    "Song: #@name--#@artist(#@duration)"
  end
end

类的实例化:

1
2
song = Song.new("Bicyclops", "Fleck", 260)
song.to_s

继承:

1
2
3
4
5
6
class KaraoKeSong < Song
  def initialize(name, artist, duration, lyrics){
      super(name, artist, duration)
      @lyrics = lyrics
  end
end

读对象的属性

1
2
3
class Song
  attr_reader :name, :artist, :duration
end

可写的属性,创建一个名字以等号结尾的方法来设置对象属性,或者使用attr_writer

1
2
3
class Song
  attr_writer :duration
end

类变量,只存在一份拷贝,由@@开头,例如@@count

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Song
  @@plays = 0
  def initialize(name, artist, duration)
      @name       = name
      @artist = artist
      @duration   = duration
      @plays      = 0
  end
  def play
      @plays += 1 #same as @plays = @plays + 1
      @@plays += 1
      "This song:# #@plays plays. Total #@@plays plays."
  end
end

类方法,通过在方法名之前放置类名以及一个句点来定义

1
2
3
4
5
6
class Example
  def instance_method  #实例方法
  end
  def Example.class_method  #类方法
  end
end

单例模式

1
2
3
4
5
6
7
8
class MyLogger
  private_class_method :new
  @@logger = nil
  def MyLogger.create
      @@logger = new unless @@logger
      @@logger
  end
end

访问控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Accounts
  def initialize(checking, savings)
      @checking = checking
      @savings = savings
  end
private
  def debit(account, amount)
      account.balance -= amount
  end
  def credit(account, amount)
      account.balance += amount
  end
public
  def transfer_to_savings(amount)
      debit(@checking, amount)
      credit(@savings, amount)
  end
end