Ruby 面向对象


Ruby面向对象编程

什么是面向对象编程

面向对象编程(Object-Oriented Programming)是一种编程范型,它将数据和操作数据的方法组合成为对象,通过对对象进行分类和组合来创建程序和应用。

面向对象编程的核心概念就是类和对象。类是用来描述对象的一种抽象,而对象则是实际的实例。

Ruby是一种纯面向对象编程语言,它的所有基本数据类型都是对象。

Ruby中的类和对象

在Ruby中定义类,需要使用关键字class和类名,如下:

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

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

其中,initialize函数相当于构造函数,在对象创建时自动调用,设置对象的初始状态。

对象

在Ruby中创建对象,需要使用new方法,如下:

person = Person.new("Tom")
person.say_hello # output: Hello, I'm Tom

成员变量和方法

在Ruby中,类的成员变量以@开头,如上述例子中的@name。同时,在类中,通过def定义方法,可以在对象创建后调用。

继承

在Ruby中,继承使用关键字<,如下:

class Student < Person
  def initialize(name, grade)
    super(name)
    @grade = grade
  end

  def show_grade
    puts "#{@name}'s grade is #{@grade}"
  end
end

student = Student.new("Jerry", 90)
student.say_hello # output: Hello, I'm Jerry
student.show_grade # output: Jerry's grade is 90

上述代码中,Student类继承自Person类,并添加了自己的属性和方法。

Mixin

Mixin是Ruby的一个特色,它使得在类中简单地引入其它模块中的方法。如下:

module GoodStudent
  def do_homework
    puts "#{@name} is doing homework."
  end
end

class SuperStudent < Student
  include GoodStudent
end

super_student = SuperStudent.new("James", 100)
super_student.say_hello # output: Hello, I'm James
super_student.do_homework # output: James is doing homework.

通过使用include方法,将GoodStudent模块中的do_homework方法引入到SuperStudent类中。

小结

Ruby作为一种早期就面向对象的编程语言,它的面向对象编程十分精湛,具有深刻的哲学内涵和强大的抽象能力。类和对象的定义清晰明了,继承和Mixin使得代码的重复使用和扩展都变得十分方便。