ruby之attr_reader,attr_writer,attr_accessor

attr_accessor用于创建读取和设置实例变量的方法,例如attr_accessor :price,则相当于创建price方法用于读取@price的值,创建price=(yourprice)方法用于将@price的值设置为yourprice
attr_reader则只创建读取实例变量的方法
attr_writer只创建为实例变量赋值的方法
请看下面的例子详解:
例1
class Person
end

person = Person.new
person.name # 此处报错,提示no method errorObviously we never defined method name. Let's do that.

例2
class Person
  def name
    @name    # simply returning an instance variable @name
  end
end

person = Person.new
person.name # 不会报错,返回值为 nil
person.name = "Dennis" # 报错,提示 no method errorAha, we can read the name, but that doesn't mean we can assign the name. Those are two different methods. Former called reader and latter called writer. We didn't create the writer yet so let's do that.

例3
class Person
  def name
    @name
  end

  def name=(str)
    @name = str
  end
end

person = Person.new
person.name = 'Dennis'
person.name # 返回值为 "Dennis"

ruby提供了attr_accessor、attr_reader、attr_writer来让程序员免去编写上面类似代码的重复性工作。
例4
class Person
  attr_reader :name
  attr_writer :name
end

person = Person.new
person.name = "Dennis"
person.name # 返回值为"Dennis"

例5
class Person
  attr_accessor :name

  def greeting
    "Hello #{@name}"
  end
end

person = Person.new
person.name = "Dennis"
person.greeting  # 打印"Hello Dennis"
现在明白了attr的三个类型的用法了吧!

你可能感兴趣的:(attr_accessor,attr_reader,attr_writer)