当前位置:首页 > 建站学院 > 后端开发 >  Ruby面向对象

Ruby面向对象

后端开发   发布日期:2025年07月11日   浏览次数:110

​ Ruby是真正的面向对象语言,一切皆为对象,甚至基本数据类型都是对象

基本用法

  1. class Box
  2. # 构造函数
  3. def initialize(w,h)
  4. @with, @height = w, h #加@的是实例变量
  5. end
  6. # get方法
  7. def getWidth
  8. @with # 默认最后一条语句的返回值作为函数返回值
  9. end
  10. def getHeight
  11. @height
  12. end
  13. # set方法
  14. def setWidth(w)
  15. @with = w
  16. end
  17. # 实例方法
  18. def getArea
  19. @with * @height
  20. end
  21. end
  22. box = Box.new(10, 20)
  23. box.setWidth 15
  24. puts box.getWidth
  25. puts box.getHeight
  26. puts box.getArea

简化get,set

​ Ruby中,实例变量前面要加@,外部无法直接读写,要自己写get,set方法来访问。Ruby提供了一种方便的属性声明方法来更方便地做访问控制:

  1. class Box
  2. # 声明外部可读,要用符号类型
  3. attr_reader :label
  4. # 声明外部可写
  5. attr_writer :width, :height
  6. def initialize(w,h,label)
  7. @width, @height = w, h
  8. @label = label
  9. end
  10. def getArea
  11. @width * @height
  12. end
  13. end
  14. box = Box.new(10, 20,'box')
  15. puts box.label
  16. box.width = 15
  17. puts box.getArea

​ attr_accessor声明相当于reader+writer

类变量&类变量

​ 类变量前面加上@@就可以,类方法只要前面加上self即可

  1. class Box
  2. # 初始化类变量
  3. @@count = 0
  4. def initialize(w,h)
  5. @width, @height = w, h
  6. @@count += 1
  7. end
  8. # 类方法
  9. def self.printCount
  10. puts "Box count is #{@@count}"
  11. end
  12. end
  13. box1 = Box.new(10, 20)
  14. box2 = Box.new(15, 20)
  15. Box.printCount

方法访问控制

​ 我们经常会对类做一些封装,因此访问控制还是必要的。Ruby的成员变量的访问控制在前面用get、set访问控制已经解决。方法的控制有三个级别:

  • public:默认情况下,除了initialize方法是private,其他都是public的
  • private:只有类内可以访问
  • protected:可以在类内和子类中使用

举例

  1. class Box
  2. def initialize(w,h)
  3. @width, @height = w, h
  4. end
  5. def getArea
  6. caculate
  7. @area
  8. end
  9. def caculate
  10. @area = @width * @height
  11. end
  12. # 方法的权限控制声明
  13. private :caculate
  14. end
  15. box = Box.new(10, 20)
  16. puts box.getArea

继承

  1. # 定义基类
  2. class Box
  3. def initialize(w,h)
  4. @width, @height = w, h
  5. end
  6. def getArea
  7. @width*@height
  8. end
  9. end
  10. # 定义子类
  11. class BigBox < Box
  12. def printArea
  13. # 继承基类方法和变量
  14. puts getArea
  15. end
  16. end
  17. box = BigBox.new(10,20)
  18. box.printArea

方法重载&运算符重载

  1. class Box
  2. attr_reader :width, :height
  3. def initialize(w,h)
  4. @width, @height = w,h
  5. end
  6. def getArea
  7. @width*@height
  8. end
  9. end
  10. class BigBox < Box
  11. # 重载方法
  12. def getArea
  13. @area = @width * @height
  14. puts "Big box area is: #{@area}"
  15. end
  16. # 运算符重载
  17. def +(other) # 定义 + 来执行向量加法
  18. BigBox.new(@width + other.width, @height + other.height)
  19. end
  20. end
  21. box1 = BigBox.new(10,20)
  22. box2 = BigBox.new(5,10)
  23. box1.getArea
  24. box3 = box1+box2
  25. box3.getArea

小结

​ Ruby中的面向对象应该说非常简洁优雅,不愧是纯粹的面向对象语言。

以上就是Ruby面向对象的详细内容,更多关于Ruby面向对象的资料请关注九品源码其它相关文章!