使用 getter 和 setter 访问实例变量

我们有三种方法:

  1. attr_reader :用于允许在课堂外传递变量。
  2. attr_writer :用于允许修改类外的变量。
  3. attr_accessor :结合两种方法。
class Cat
  attr_reader :age # you can read the age but you can never change it
  attr_writer :name # you can change name but you are not allowed to read
  attr_accessor :breed # you can both change the breed and read it

  def initialize(name, breed)
    @name = name
    @breed = breed
    @age = 2 
  end
  def speak
    puts "I'm #{@name} and I am a #{@breed} cat"
  end
end
 
my_cat = Cat.new("Banjo", "birman")
# reading values:

my_cat.age  #=> 2
my_cat.breed #=> "birman"
my_cat.name #=> Error

# changing values
 
my_cat.age = 3 #=> Error
my_cat.breed = "sphynx" 
my_cat.name = "Bilbo"

my_cat.speak #=> I'm Bilbo and I am a sphynx cat

请注意,参数是符号。这通过创建方法来工作。

class Cat
  attr_accessor :breed
end

基本相同:

class Cat
  def breed
    @breed
  end
  def breed= value
    @breed = value
  end
end