Menu
CoddyTech

实例变量

本课属于 Coddy Ruby 学习旅程的“面向对象编程”单元。第 3 课,共 57 课。

实例变量以 @ 开头,属于一个对象。存储在 initialize 中的值会一直可供该对象的每个方法使用,而且每个实例都有自己的副本:

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

  def speak
    "#{@name} says Woof"
  end
end

rex = Dog.new("Rex")
bella = Dog.new("Bella")
puts rex.speak
puts bella.speak

输出:

Rex says Woof
Bella says Woof

方法可以更改 instance_variables,因此对象会记住发生在它身上的事情。所有实例变量共同构成对象的状态:

class Counter
  def initialize
    @count = 0
  end

  def increment
    @count += 1
  end

  def report
    "count is #{@count}"
  end
end

clicks = Counter.new
clicks.increment
clicks.increment
puts clicks.report

输出:

count is 2

无法从对象外部访问实例变量。外部代码只能调用方法,所以想要共享某个值的类会定义一个返回该值的方法,也就是读取器:

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

  def name
    @name
  end
end

rex = Dog.new("Rex")
puts rex.name
begin
  rex.age
rescue NoMethodError => e
  puts e.message
end

输出:

Rex
undefined method `age' for an instance of Dog

从未赋值的实例变量是 nil,不会引发错误,因此拼错的名称会悄悄读取另一个空变量。instance_variables 会列出对象实际拥有的变量:

class Lamp
  def initialize
    @on = false
  end

  def status
    @onn.inspect
  end
end

lamp = Lamp.new
puts lamp.status
p lamp.instance_variables

输出:

nil
[:@on]
challenge icon

挑战

简单

完成 Pet 类。initialize(name, species, age) 用于存储这三个值,birthday 会让年龄增加 1 岁,而 describe 会返回一个句子:一只名为 Rex、种类为 dog、年龄为 3 的宠物会得到 Rex is a 3 year old dog。

提供的代码会根据输入的前三行(名称、种类、年龄)创建一个 Pet,按照第四行指定的次数调用 birthday,并输出 describe 的结果。

你的代码要写在 pet.rb 中。main.rb 包含提供的输入/输出代码,不能编辑。

亲手试试

require_relative 'pet'

# 提供的输入输出代码:保持原样。
input = []
while (line = gets)
  input << line.chomp
end
pet = Pet.new(input[0], input[1], input[2].to_i)
input[3].to_i.times { pet.birthday }
puts pet.describe
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向对象编程中的所有课

自己练习: Ruby 在线编译器