2.9. 核心语言——对象,类,方法-4

未匹配的标注

读取实例变量

有时候我们想能够从对象外面去读取实例变量,我们可以写一个方法来做这件事情:

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

  def name # 就这个方法
    @name
  end
end

bot = Robot.new("Eve")
puts bot.name # returns "Eve"

image-20221004194650062

使用 new 方法实例化对象 bot 时,把这个 “Eve” 传到他 initialize 方法里面,实例变量 @name = “Eve”。然后用 bot.name 这个是调用对象 name 方法,返回 @name。

attr_reader

然而,Ruby 为做这个事情为提供了一个简写的方式,叫做 attr_reader。下面的类和上面的等价:

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

  attr_reader :name
end

bot = Robot.new("hustnzj")
puts bot.name # returns "hustnzj"

image-20221004195340693

attr_reader 接收一系列名称,对每个名称都产生一个暴露同名实例变量的方法。

attr_writer

类似的,attr_writer 产生一个从对象外部对实例变量进行赋值的方法。表达式 :name 是一个符号,我们后面会更详细介绍。

class Robot
  attr_writer :name
end

bot = Robot.new
bot.name = "Eve"

p bot
# bot now has an instance variable @name with the value "Eve"

image-20221004200407477

表面上看起来我们这个 bot.name = “Eve” 是对属性赋值,但是它实际上是一个方法调用。它调用了一个叫做 name= 的方法,这个等号一定要有。

明确定义 name= 方法

如果不用 attr_writer 可以明确的写出这个方法如下:

class Robot
  def name=(name)
    @name = name
  end 
end

bot = Robot.new
bot.name = "hustnzj"

p bot
# bot now has an instance variable @name with the value "hustnzj"

image-20221004201003442

attr_accessor

一个 reader 和 writer 在使用 attr_accessor 定义在一个单一的表达式中。

attr_reader :name
attr_writer :name

attr_accessor :name

等价。

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

  attr_accessor :name
end

bot = Robot.new("hustnzj")
puts bot.name # attr_reader :name

bot.name = "Eve" # attr_writer :name
puts bot.name # "Eve"

image-20221004201721977

Here is a reference of attr_accessor

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 查看所有版本


暂无话题~