I didn't understand the scope of class fields, class methods, instance methods, and the scope of effect of instance variables, so I summarized them.
My understanding has deepened, but a new mystery has emerged.
I would appreciate it if you could tell me any suggestions or supplements.
class Zoo
def self.kind(animal_name)
@animal_name = animal_name
puts @animal_name #output:Giraffe
puts animal_name #output:Giraffe
puts @name #output:Blank
puts name #output:Zoo
end
def self.kind_name
puts @animal_name #output:Giraffe
# puts animal_name #output:NameError
end
puts @animal_name #output:Blank
# puts animal_name #output:NameError
def initialize(new_animal)
@new = new_animal
puts "#{@new}Has increased." #output:新たな仲間Has increased.
end
def kind(name)
@name = name
puts @animal_name #output:Blank
# puts animal_name output:NameError
puts @name #output:Lion
puts name #output:Lion
end
puts @name #output:Blank
puts name #output:Zoo
def color(animal_color)
@color = animal_color
#puts name output:NameError
puts "#{@new}of#{@name}Is#{@color}is" #output:新たな仲間ofライオンIs黄色is
#puts name output:NameError
end
end
Zoo.kind("Giraffe")
#Class method self.Kind execution
Zoo.kind_name
#Class method self.kind_Run name
animal = Zoo.new("New companion")
#Create animal instance, execute initialize method
puts animal.kind("Lion")
#Kind instance method execution of animal instance
puts animal.color("yellow")
#Execute color instance method of animal instance
#↓ Out of scope
# puts @animal_name output:Blank
# puts animal_name output:NameError
# puts @name output:Blank
#puts name output:NameError
Zoo
Giraffe
Giraffe
Zoo
Giraffe
New friends have been added.
Lion
Lion
The new fellow lion is yellow
-The output contents will be the contents read in order from the top including the class part.
-Instance variables are between class methods or between instance methods. It is possible to output each other. However, since you cannot create an instance in the class method, @ Is just a pipe that connects class methods.
-Instance variables do not cause NameError even if they are placed outside the scope, It creates a blank in the output destination.
-Why in a class field other than an instance method (including a class method) Is the class name output when an undefined name is output?
Recommended Posts