要深入理解Ruby面向?qū)ο缶幊蹋∣OP),您需要了解以下幾個方面:
class
關(guān)鍵字創(chuàng)建類,使用new
方法創(chuàng)建對象。class Dog
attr_accessor :name, :breed
def initialize(name, breed)
@name = name
@breed = breed
end
def bark
puts "Woof!"
end
end
my_dog = Dog.new("Buddy", "Golden Retriever")
my_dog.bark
extends
關(guān)鍵字實現(xiàn)繼承。class Animal
attr_accessor :name
def initialize(name)
@name = name
end
def speak
puts "I am an animal."
end
end
class Dog < Animal
def bark
puts "Woof!"
end
end
my_dog = Dog.new("Buddy")
my_dog.speak
my_dog.bark
attr_reader
和attr_writer
創(chuàng)建訪問器和修改器方法。class Person
attr_reader :name, :age
def initialize(name, age)
@name = name
@age = age
end
def birthday
@age += 1
end
end
my_person = Person.new("Alice", 30)
puts my_person.name # 輸出 "Alice"
puts my_person.age # 輸出 30
my_person.birthday
puts my_person.age # 輸出 31
def
關(guān)鍵字)和方法重載(使用initialize
方法的重載)實現(xiàn)多態(tài)。class Animal
def speak
puts "I am an animal."
end
end
class Dog < Animal
def speak
puts "Woof!"
end
end
class Cat < Animal
def speak
puts "Meow!"
end
end
animals = [Dog.new("Buddy"), Cat.new("Kitty")]
animals.each do |animal|
animal.speak
end
include
關(guān)鍵字將模塊包含到類中。module Canine
def bark
puts "Woof!"
end
end
class Dog
include Canine
attr_accessor :name, :breed
def initialize(name, breed)
@name = name
@breed = breed
end
end
my_dog = Dog.new("Buddy", "Golden Retriever")
my_dog.bark
通過深入了解這些概念并在實際項目中應(yīng)用它們,您將能夠熟練掌握Ruby面向?qū)ο缶幊獭?/p>