创建类和对象
定义类
class Dog
def bark
puts "Woof!"
end
end
创建对象
my_dog = Dog.new
实例变量和方法
实例变量
实例变量以 @ 开头,用于在对象中存储数据:
class Person
def initialize(name)
@name = name
end
def greet
puts "Hello, #{@name}!"
end
end
person = Person.new("John")
person.greet
方法
类中的函数被称为方法,可以通过对象调用:
class Calculator
def add(x, y)
x + y
end
def subtract(x, y)
x - y
end
end
calculator = Calculator.new
sum = calculator.add(3, 5)
difference = calculator.subtract(8, 3)
puts "Sum: #{sum}"
puts "Difference: #{difference}"
属性访问器和修改器
class Car
# 读取器
attr_reader :model
# 修改器
attr_writer :color
# 读取器和修改器
attr_accessor :speed
def initialize(model, color, speed)
@model = model
@color = color
@speed = speed
end
end
my_car = Car.new("Toyota", "Blue", 60)
puts "Model: #{my_car.model}"
puts "Color: #{my_car.color}" # 无法调用,因为 color 只有写入权限
puts "Speed: #{my_car.speed}"
my_car.color = "Red"
puts "New Color: #{my_car.color}"
继承
class Animal
def speak
puts "Animal speaks"
end
end
class Dog < Animal
def bark
puts "Woof!"
end
end
class Cat < Animal
def meow
puts "Meow!"
end
end
dog = Dog.new
dog.speak # 继承自 Animal 类
dog.bark
cat = Cat.new
cat.speak # 继承自 Animal 类
cat.meow
模块
module Greetable
def greet
puts "Hello!"
end
end
class Person
include Greetable
end
person = Person.new
person.greet
这是 Ruby 面向对象编程的一些基本概念。Ruby 的面向对象特性使得代码更加模块化和易于维护。如有其他问题,请随时提问。
转载请注明出处:http://www.pingtaimeng.com/article/detail/13441/Ruby