[Ruby] About attr_accessor

1 minute read

What is an instance variable?

Variables shared within the same instance

``


class Food
  def initialize(name)
# Save the name passed at instance creation in the instance variable
@Name = name
  end

  def eat
"I will eat an #{@name}"
  end
end
food = Food.new('apple')
food.hello #=> "I will eat an apple"

Instance variables cannot be referenced from outside the class!

``


class Food
  def initialize(name)
@Name = name
  end

  Method for externally referencing #@name
  def name
@Name
  end
end
food = Food.new('apple')
Get the contents of @name via #name method
food.name #=> "apple"

If you want to change the contents of the instance variable from the outside, define a method for changing

``


class Food
  def initialize(name)
@Name = name
  end

  Method for externally referencing #@name
  def name
@Name
  end

Method to change #@name from the outside
  def name=(value)
    @name = value
  end
end
food = Food.new('apple')
It looks like you're assigning to a #variable, but it's actually calling the name= method.
food.name ='banana'
Get the contents of @name via #name method
food.name #=> "banana"

A method that reads and writes the value of an instance variable is called an “accessor method”. It is troublesome to write these methods one by one. That’s where the “attr_accessor method” comes in.

attr_accessor method

``


class Food
  Methods to read and write #@name are automatically defined
  attr_accessor :name

  def initialize(name)
@Name = name
  end

  Method for externally referencing #@name
  #def name
#@Name
  #end

Method to change #@name from the outside
  #def name=(value)
#@name = value
  #end
end
food = Food.new('apple')
Change #@name
food.name ='banana'
Refer to #@name
food.name #=> "banana"

“Attr_reader” when you want to make the contents of the instance variable read-only “Attr_writer” if you want to write only

reference Introduction to Ruby for professionals

Tags:

Updated: