Ruby
--Those who are not aware of variable types. --Those who have just studied programming --Those who do not understand variables ――When NoMethodError occurs in Ruby, I can't think of the cause.
We do not explain difficult parts of variables and types (reference type, value type, null, scope, etc.), but create it so that you can grasp the image of the variable.
Only this. This is as important as it is static or dynamic. The image is like this.
Programmers who are unaware of the contents of variables often write this way.
Variable! Please cook! !!
You don't know that the contents of the variable are carpenters. So I tell the carpenter to cook. The code is as follows.
#Defines a carpenter class.
class Carpenter
#Defines a construction method.
def construction
puts "To build"
end
end
#It materializes the carpenter class.
hennsuu = Carpenter.new
#You are calling a method that is not defined in the carpenter class.
hennsuu.cooking
Do you understand? I will explain it again using a class that actually exists. See the official documentation for the String and Integer classes in Ruby.
Search for upcase in the site (command + F). A String will hit, but an Integer will not. This means that the String class has an upcase method defined, but the Integer class does not have an upcase method defined. Now let's actually execute the code.
hennsuu = "abcdef"
puts hennsuu.upcase #"ABCDEF"
hennsuu2 = 12345
puts hennsuu2.upcase #NoMethodError
hennsuu.class # String
hennsuu.class # Integer
You got a NoMethod error. This is an error because the upcase method is not defined in the Integer class. In this way, you cannot write a program without being aware of the contents of variables, or more specifically, without being aware of the classes of the contents of variables.
You may suffer from unexpected bugs and errors if you are not aware of the contents of the variables. Be aware of the contents of variables!
The cute picture used this time was obtained from the following site. The copyright of the material is held by Mr. Takashi Mifune. https://www.irasutoya.com/
Recommended Posts