[Ruby] [Ruby] Forget what attr_reader, attr_writer, and attr_accessor are doing many times

less than 1 minute read

I write it as a memorandum because I am left vague after checking each time.

Overview

attr_reader

Define a read method for the instance variable name.

Quotation source: https://docs.ruby-lang.org/ja/latest/method/Module/i/attr_reader.html

class Human
  #Defined here
  attr_reader :name

  def initialize(name)
    @name = name
  end
end

# Instance generation from here

human1 = Human.new(sato)
p human1.name
# => sato

attr_writer

Define a write method (name=) to the instance variable name.

Quotation source: https://docs.ruby-lang.org/ja/latest/class/Module.html#I_ATTR_ACCESSOR


class Human
  #Defined here
  attr_writer :name

  def initialize(name)
    @name = name
  end
end

# Instance generation from here

human1 = Human.new(sato)

Readable thanks to #attr_render
p human1.name
# => sato

Can be changed thanks to #attr_writer
human1.name ='kato'

# Value has changed
p human1.name
# => kato

attr_accessor

Attr_reader and attr_writer with two functions