Variables shared inside the same instance
python
class Food
def initialize(name)
#Save the name passed when creating the instance 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!
python
class Food
def initialize(name)
@name = name
end
#@Method for referencing name from the outside
def name
@name
end
end
food = Food.new('apple')
#Via the name method@Get the contents of name
food.name #=> "apple"
If you want to change the contents of an instance variable from the outside, define a method for changing
python
class Food
def initialize(name)
@name = name
end
#@Method for referencing name from the outside
def name
@name
end
#@Method for changing name from the outside
def name=(value)
@name = value
end
end
food = Food.new('apple')
#It looks like you're assigning it to a variable, but it's actually a name=You are calling a method.
food.name = 'banana'
#Via the name method@Get the contents of name
food.name #=> "banana"
A method that reads and writes the value of an instance variable is called an "accessor method". Writing these methods one by one is a hassle. That's where the "attr_accessor method" comes in.
python
class Food
#@Methods to read and write name are automatically defined
attr_accessor :name
def initialize(name)
@name = name
end
#@Method for referencing name from the outside
#def name
#@name
#end
#@Method for changing 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" if you want to make the contents of the instance variable read-only If you want to write only, "attr_writer"
reference An introduction to Ruby for those who want to become professionals
Recommended Posts