Ruby类与对象 #

一、面向对象概述 #

Ruby是一门纯粹的面向对象语言,一切皆对象。类是对象的蓝图,对象是类的实例。

二、定义类 #

2.1 基本语法 #

ruby
class Person
end

person = Person.new
person.class

2.2 类命名 #

ruby
class Person
end

class UserProfile
end

class HTTPClient
end

class XMLParser
end

2.3 类是对象 #

ruby
Person.class
Person.superclass
Person.class.superclass

三、创建对象 #

3.1 new方法 #

ruby
class Person
end

person = Person.new
person.class
person.object_id

3.2 initialize方法 #

ruby
class Person
  def initialize(name, age)
    @name = name
    @age = age
  end
end

person = Person.new("Ruby", 30)

3.3 默认参数 #

ruby
class Person
  def initialize(name = "Unknown", age = 0)
    @name = name
    @age = age
  end
end

person1 = Person.new
person2 = Person.new("Ruby")
person3 = Person.new("Rails", 20)

四、实例变量 #

4.1 定义实例变量 #

ruby
class Person
  def initialize(name)
    @name = name
  end

  def name
    @name
  end

  def name=(new_name)
    @name = new_name
  end
end

person = Person.new("Ruby")
person.name
person.name = "Rails"
person.name

4.2 attr系列方法 #

ruby
class Person
  attr_reader :name
  attr_writer :email
  attr_accessor :age

  def initialize(name, age)
    @name = name
    @age = age
  end
end

person = Person.new("Ruby", 30)
person.name
person.age
person.age = 31
person.email = "ruby@example.com"

4.3 attr_reader vs attr_writer vs attr_accessor #

ruby
class Example
  attr_reader :read_only
  attr_writer :write_only
  attr_accessor :read_write

  def initialize
    @read_only = "只读"
    @write_only = "只写"
    @read_write = "读写"
  end
end

obj = Example.new
obj.read_only
obj.read_only = "new"
obj.write_only = "new"
obj.write_only
obj.read_write
obj.read_write = "new"

五、实例方法 #

5.1 定义方法 #

ruby
class Person
  def initialize(name)
    @name = name
  end

  def greet
    "Hello, I'm #{@name}"
  end

  def introduce
    "#{greet}. Nice to meet you!"
  end
end

person = Person.new("Ruby")
person.greet
person.introduce

5.2 方法调用 #

ruby
class Calculator
  def add(a, b)
    a + b
  end

  def multiply(a, b)
    a * b
  end

  def calculate(a, b)
    add(a, b) * multiply(a, b)
  end
end

calc = Calculator.new
calc.add(1, 2)
calc.calculate(2, 3)

5.3 self #

ruby
class Person
  def initialize(name)
    @name = name
  end

  def name
    @name
  end

  def introduce
    "I'm #{self.name}"
  end

  def self.species
    "Human"
  end
end

person = Person.new("Ruby")
person.introduce
Person.species

六、类方法 #

6.1 定义类方法 #

ruby
class Person
  def self.create(name)
    Person.new(name)
  end

  class << self
    def default
      Person.new("Default")
    end
  end
end

person = Person.create("Ruby")
person = Person.default

6.2 类变量 #

ruby
class Person
  @@count = 0

  def initialize
    @@count += 1
  end

  def self.count
    @@count
  end
end

Person.new
Person.new
Person.count

6.3 类实例变量 #

ruby
class Person
  @default_name = "Unknown"

  def self.default_name
    @default_name
  end

  def self.default_name=(name)
    @default_name = name
  end
end

Person.default_name
Person.default_name = "Default"
Person.default_name

七、构造模式 #

7.1 工厂方法 #

ruby
class Person
  def initialize(name, age)
    @name = name
    @age = age
  end

  def self.create_adult(name)
    Person.new(name, 18)
  end

  def self.create_child(name)
    Person.new(name, 10)
  end

  def self.from_hash(hash)
    Person.new(hash[:name], hash[:age])
  end
end

adult = Person.create_adult("Ruby")
child = Person.create_child("Kid")
person = Person.from_hash({ name: "Test", age: 25 })

7.2 构建器 #

ruby
class Person
  attr_reader :name, :age, :email, :city

  def initialize
    @name = "Unknown"
    @age = 0
    @email = ""
    @city = ""
  end

  def set_name(name)
    @name = name
    self
  end

  def set_age(age)
    @age = age
    self
  end

  def set_email(email)
    @email = email
    self
  end

  def set_city(city)
    @city = city
    self
  end
end

person = Person.new
  .set_name("Ruby")
  .set_age(30)
  .set_email("ruby@example.com")
  .set_city("Beijing")

八、实用示例 #

8.1 银行账户 #

ruby
class BankAccount
  attr_reader :balance, :owner

  def initialize(owner, initial_balance = 0)
    @owner = owner
    @balance = initial_balance
    @transactions = []
  end

  def deposit(amount)
    @balance += amount
    @transactions << { type: :deposit, amount: amount, balance: @balance }
  end

  def withdraw(amount)
    return false if amount > @balance

    @balance -= amount
    @transactions << { type: :withdraw, amount: amount, balance: @balance }
    true
  end

  def transactions
    @transactions.dup
  end
end

account = BankAccount.new("Ruby", 1000)
account.deposit(500)
account.withdraw(200)
account.balance

8.2 购物车 #

ruby
class ShoppingCart
  def initialize
    @items = []
  end

  def add_item(product, quantity = 1)
    @items << { product: product, quantity: quantity }
  end

  def remove_item(product)
    @items.reject! { |item| item[:product] == product }
  end

  def total
    @items.sum { |item| item[:product].price * item[:quantity] }
  end

  def items
    @items.dup
  end

  def clear
    @items.clear
  end
end

8.3 日志记录器 #

ruby
class Logger
  LEVELS = { debug: 0, info: 1, warn: 2, error: 3 }

  def initialize(level = :info)
    @level = LEVELS[level]
  end

  def debug(message)
    log(:debug, message) if @level <= LEVELS[:debug]
  end

  def info(message)
    log(:info, message) if @level <= LEVELS[:info]
  end

  def warn(message)
    log(:warn, message) if @level <= LEVELS[:warn]
  end

  def error(message)
    log(:error, message) if @level <= LEVELS[:error]
  end

  private

  def log(level, message)
    timestamp = Time.now.strftime("%Y-%m-%d %H:%M:%S")
    puts "[#{timestamp}] #{level.to_s.upcase}: #{message}"
  end
end

logger = Logger.new(:debug)
logger.info("Application started")
logger.error("Something went wrong")

九、总结 #

本章我们学习了:

  1. 定义类:class关键字、命名规则
  2. 创建对象:new方法、initialize
  3. 实例变量:@变量、attr系列方法
  4. 实例方法:定义、调用、self
  5. 类方法:self.method、class << self
  6. 类变量:@@变量、类实例变量
  7. 构造模式:工厂方法、构建器

接下来让我们学习Ruby的属性与方法!

最后更新:2026-03-27