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

After checking each time, it will remain vague, so write it down as a memorandum.

Overview

attr_reader

Define a method to read the instance variable name.

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

#Instantiate from here

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

attr_writer

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

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

#Instantiate from here

human1 = Human.new(sato)

#attr_Readable thanks to render
p human1.name
# => sato

#attr_Can be changed thanks to writer
human1.name = 'kato'

#The value has changed
p human1.name
# => kato

attr_accessor

It has two functions, attr_reader and attr_writer.

Recommended Posts

[Ruby] Forget what attr_reader, attr_writer, attr_accessor are doing many times
What are Ruby class methods?
config.ru What are you doing?
Find out what many threads are doing from the jstack results
bundle install? yarn install? What are you doing