A method that reads and writes the value of an instance variable. Ruby is designed so that instance variables cannot be accessed as it is.
(Example)
class Animal
@name = ""
end
animal = Animal.new
animal.name = "cat"
puts animal.name # => ruby.rb:6:in `<main>': undefined method `name=' for #<Animal:0x00007fce4a8b4b40> (NoMethodError)
According to this code definition method, @name is defined as a different variable called "class instance variable", which is inaccessible from the instance.
How should I define the instance variables that can be accessed from the instance?
So we use the "accessor method".
First, there are three types of accessor methods.
attr_reader attr_reader is a getter for accessing instance variables.
(Example)
class Animal
attr_reader :name
def initialize(name)
@name = name
end
end
animal = Animal.new("cat")
puts animal.name # => cat
In this way, you can access the instance variable @name by writing attr_reader: name. However, as it is, the setter is not defined, so @name cannot be changed from outside the class.
attr_writer attr_writer is a setter for accessing instance variables.
(Example)
class Animal
attr_writer :name
attr_reader :name
def initialize(name)
@name = name
end
end
animal = Animal.new("cat")
puts animal.name
animal.name = "dog"
puts animal.name
# => cat
# dog
In this way, by writing attr_writer: name in addition to attr_reader: name, you can change and access the instance variable @name from the outside.
attr_accessor This method combines the functions of attr_reader and attr_writter.
(Example)
class Animal
attr_accessor :name
def initialize(name)
@name = name
end
end
animal = Animal.new("cat")
puts animal.name
animal.name = "dog"
puts animal.name
# => cat
# dog
In this way, you can change the instance variable @name from the outside and access it.
Recommended Posts