Introduction to Ruby Language (4) - Using Class Programming and Advanced Functions
Introduction to Ruby Language (4) - Using Class Programming and Advanced Functions
Continuation of Ruby language introduction (3) - Ruby flow control statements and practical data processing
Topic: Template
Explanation: Some settings about the template
Topic: x
Elaboration: y
Table of contents
Topic: Template
Topic: Programming with classes
Topic: Understanding Object-Oriented Concepts
Topic: Class
Topic: Constructor
Topic: Method
Topic: Scope Modifiers
Topic: Inherited Classes
Topic: Ruby Advanced Features
Topic: Modules
Topic: Threads
Topic: Other Dynamic Language Features
Topic: Programming with classes
Explanation: Object-oriented is a programming method that uses "data control access code" as the main principle to organize programs around data. Classes are the core of object-oriented programming . They can not only include their own members, but also inherit through relationships to achieve code reuse.
Then the concept of object-oriented is introduced, and then the focus is on how to define classes, instantiate classes, class constructors, class methods, class variables, attributes, etc. in Ruby. Finally, we introduce the use of inheritance between classes, and access to the constructors and methods of the base class during inheritance.
Topic: Understanding Object-Oriented Concepts
Explanation: The so-called object-oriented technology is used to solve problems. Treat the object as an entity and encapsulate the characteristics and behavior of the object into a class so that other programs can call it when performing the same function to achieve the purpose of code reuse.
The yard-oriented thinking has three major mechanisms, which can also be said to be the three major mechanisms of classes, namely encapsulation, inheritance and polymorphism.
what is object
Object-oriented programming uses objects to simulate the real world. An object is anything in the real world. Objects can also represent abstract rules, plans, and events.
All data and code contained in an object can form a user-defined data type through classes. In fact, objects are class type variables. A class is an abstraction of identical or similar objects. Therefore, the abstraction of an object is a class, and the concretization of a class is an object. It can also be said that an instance of a class is an object. Once a class is defined, multiple objects of that class can be created. Each object is related to a set of data, and the type of this set of data is defined in the class. Therefore, a class is an abstraction of objects of the same type.
The essence of object-oriented design thinking is that everything is an object. Software development and design are centered around the development goal, that is, developing and designing around objects. Generally speaking an object should have properties and behavior.
In object-oriented programming, the state of an object can be described using a set of data values. Objects also have behavior, that is, the object and its operations are the behavior of the object. Objects realize the combination of data and operations, so that data and operations are encapsulated in the unity of objects.
encapsulation
Encapsulation is the basic foundation, which means hiding the relevant implementation details of a class, and concentrating the data and code for implementing operations in the class and placing them inside the object. When calling these, just use the interface reserved by the class.
inherit
Inheritance provides a mechanism for subclasses to automatically own the data structures and methods of the parent class. It represents a relationship between classes, and the inheritance relationship can be represented by a tree relationship.
Polymorphism
Polymorphism is an important concept in object-oriented programming. It refers to the technique of making one object be viewed as another object.
Polymorphism enhances software flexibility and reusability.
Topic: Class
Explanation: A class represents the actual object to be processed in the application and is a collection of multiple objects with the same behavior and characteristics.
Define class
The first step in using object-oriented programming is to define a class. When defining a class, you can encapsulate multiple methods, properties, and variables, so that you can use the class to quickly generate objects with the same properties.
1. class ClassName
2. #analog
3. end
In Ruby a class name can be any allowed keyword.
When you define a class in Ruby, you can execute expressions defined in the class, unlike other languages that can only be used within class members. In this way, when the class definition is executed, the expression defined in the class will be executed directly. In addition, the self keyword can also be used in the class body to represent the default object or the current object.
Ruby allows you to append a class body to a defined class, add to it, and modify it. When using a class, the original class and the appended class will be merged.
The advantage of appending classes is that they can be spread out and saved into multiple files, but classes cannot be appended at will because the same class in multiple files will be merged when the class is loaded. So unless there is a design reason to define one part of the class in one place and another part of the class in another place. Otherwise it is not recommended.
instantiate class
In object-oriented programming, an object is the result of instantiation of a class. After defining it, you can call the new keyword to instantiate an object.
Topic: Constructor
Explanation: A constructor is included by default when a class is instantiated. The constructor is a special method that is mainly used to initialize the object when it is instantiated, that is, to assign initial values to the object member variables. The constructor has the following characteristics:
The name of the constructor must be initialize;
The constructor does not have any return value;
The constructor cannot be called directly, it must be automatically called when the object is instantiated through the new operator;
No other access control modifiers may be used on constructed Korean;
It can accept 0 or more parameters, and the parameter values are specified through the new operator when instantiating;
If there is no constructor defined in the class, Ruby will automatically create an empty constructor.
Note: If a class contains two methods with the same name, the latter method will completely override the previous method.
inner class
When defining a class in Ruby, you can also define another class inside the class to form a nested class. To instantiate a nested class, you need to instantiate the inner class using the format "outerclass:: innerclass.new".
In Ruby, you can also create an internal class outside of an external class using the format "class external class name:: internal class name".
Special Classes
Ruby allows you to append methods and variables to a particular object. To add class members to a specific object, you need to create a class for that object, which can also be called a special class. The syntax format is as follows:
1. class<<obj
2. #special category
3. end
Here obj is the name after instantiation, indicating that the instance is created as a special class. Any class member can be added to the special class.
Note: Other objects of the class cannot access the members of the special class, only specific objects can access the members of the special class.
Topic: methods
Description:
Defining Methods
Methods are one of the important members of a class and are mainly used to perform calculations and business logic processing.The syntax format for defining a method is as follows:
1. def methodName arg1,arg2...argN
2. #method class
3. end
As you can see from the syntax format above, methods are declared using the def keyword, followed by the method name methodName, followed by an optional list of parameters (multiple separated by commas).
In Ruby you can use "()" to pass parameters to a method.
1. def methodName(arg1,...argN)
2. #methodology
3. end
Note: When passing parameters in the I love method, be sure to pay attention to the data type of the passed parameters. If the data type of the passed parameter is different from the data type of the parameter used in the method body, an error will occur.
Using Variable Parameters for Methods
In Ruby, you can also use a shorthand way to specify that the number of parameters for a method is variable. This is done by appending an asterisk "*" to the parameter name.
Specifying parameter defaults for methods
When defining methods, it is sometimes necessary to set default values for parameters. Setting default values is as simple as assigning values to parameters using the = operator.
Note: Once you have set default values for method parameters when defining a method, you can use the default values when calling the method without passing parameters to the method.
Using Method Return Values
Every expression in Ruby has a return value. A statement that calls a method is in fact an expression, and so the call also returns a result, which is the method's return value.
The easiest way to define the return value of a method is to specify it explicitly using the return keyword, but you can also return the value of the expression implicitly without the return keyword.
Defining Class Methods
Ruby also supports methods that are directly accessible using the class name, i.e. class methods. The definition of class methods differs from the definition of instance methods in that class methods are defined by adding the class name before the method name. This is the same as defining special methods, which is because the class is treated as an object at this point.
Technique: In Ruby, you can also declare a class method as "self.class-method-name".
Defining Special Methods
In addition to instance methods and class methods, Ruby allows you to define special methods for classes. A rancid special method is a method that is appended for a specific object, and again the appended method is only valid for the pending object.
Defining Class Members
Methods, variables, and properties together form the basic components of a class.
Variables
Depending on where they are used, variables in Ruby can be categorized into instance variables and variables.
Instance Variables
Instance variables are commonly used to store data in a class and can be declared at the following locations in a program:
Top level;
The top-level method;
Classes;
Methods;
Modules;
Module methods.
Instance variables defined in top-level and top-level methods are valid for the entire program, this is because such instance variables belong to top-level Object objects. Note, however, that instance variables defined in top-level methods are valid only after the method is called. @game. the instance variable can also be defined in the class, in which case the instance variable will belong to the post-instantiation variable. Therefore. it is not possible to access class-scoped instance variables within the methods of a class. Instead. it is the instance variables defined within the method scope of the class that are instance variables of the class instance. *** Translated with www.DeepL.com/Translator (free version) ***
1. class Car
2. def go
3. puts "The car is moving.";
4. @speed = 120;
5. end
6. def Acceleration
7. puts "Speed: #{@speed} km/h";
8. end
9. end
10.
11. car = Car.new;
12. car.go;
13. car.Acceleration;
14.
15.
16. The ###### program is executed as follows
17. the car is moving
18. Speed: 120 km/h
The above code defines the class instance variable @speed in the go method of the Car class, so it can be accessed in other methods of the class.
Class Variables
Class variables can be defined in the same places in Ruby as instance variables. The variable names of class variables all need to start with "@@" and the class variable belongs to a class. So when an instance of a class changes a variable, all class variables called by the instance change.
Attributes
Object-specific things that can be set or retrieved in Ruby are called properties. Instance variables declared in a class are private attributes, i.e., when declaring a class variable, the default modifier is private, and cannot be accessed outside the class. If you want to access a private programmatic property in a class, you need to create methods that read and write the property.
1. #Example: Creating read-only properties
2. class Car
3. def initialize name,color
4. @name = name;
5. @color = color;
6. end
7. def name
8. return @name;
9. end
10. def color
11. @xolor;
12. end
13. end
14. car = Car.new "BMW", "silver-white"
15. puts "This is a #{car.color} of #{car.name} car";
The above code defines two instance variables in the constructor and folds back to give you an instance variable returned by the name method and the color method, respectively. Thus, by accessing the name and color methods, you can access the instance variables in the class from outside the class. In this way, name and color can be called read-only attributes of the class.
If you want to set an instance variable in a class from outside the class, you also need to create a method for setting the instance variable. The methods for setting instance variables are special in that they are named with an "=", i.e., "attribute name =".
There are also some built-in methods in Ruby for creating attributes in classes. These methods are mainly the following:
attr_reader method: creates read-only attributes;
attr_write method: creates write-only attributes;
attr_accessor method: creates read and write attributes;
attr method: generates read attributes and optional write attributes.
Where a value of true for the second parameter of the attr method will define read-write attributes, and if not set or set to false, read-only attributes will be created.
Topic: scope modifiers
Description:
In object-oriented programming, classes are used to encapsulate data and operations on data so that the details of the implementation are not visible to the outside of the class. In Ruby, you can use scope modifiers to control how members are shaded and displayed, and Ruby provides the following three types of scope modifier keywords:
The public keyword: Modified class members represent public members that can be accessed anywhere;
The private keyword: the modified class members are protected members; these members can only be called by other methods, not explicitly through the class object;
protected keyword: declared class members are protected members, generally the same meaning as private modified class members, but the protected modifier modifies the method can be called by the caller explicitly.
In Ruby, once a scope modifier keyword is declared in a class, all methods following the keyword take that scope, knowing that another scope is defined. If no scope modifier is declared, then methods other than the initialize method default to public scoping.
Similar methods can also be used with publicMethod.
Methods modified by the public modifier can be explicitly accessed anywhere.
Topic: Inherited Classes
Description: Inheritance is an important concept in object-oriented programming. Inheritance allows developers to quickly write a new class based on an existing class. The inherited class is often called the parent class.
Inheritance Syntax
1. class ParentClass
2. #analog
3. end
4. class SubClass < ParentCLass
5. #analog
6. end
7.
Note: In Ruby a derived class is allowed to inherit from only one class, not from two or more classes. But a base class can derive from more than one class.
Use the "<"
syntax to specify the inherited class.
Accessing Base Class Constructors
When you instantiate a derived class in Ruby, the derived class has direct access to the constructor of the base class. If the base class does not define a constructor, the derived class can also not define a constructor and use the default constructor for all, which is to call the base class's initialize method.
Inheriting methods from the base class
When a member of a derived class has the same name as a member of the base class, this case overrides a method of a class. Similarly, you can think of the methods that a derived class inherits from the base class as defined methods, and the newly defined methods that follow override the methods inherited from the base class.
Ruby does not support overloading like in Java and C++ languages. (two methods with the same method name and different argument lists). Therefore, as long as the method name in the derived class is the same as the method name in the base class, a newly defined method in the derived class overrides the method in the base class even if the parameter list of the method is different from the parameter list of the base class and the base class method.
You can call a base class method with the super keyword in Ruby. When the super keyword is used in a derived class method, Ruby automatically converts it to call a method of the same name in the base class. In other words, when a derived class defines a method of the same name in the base class, using the super keyword preserves the original method of the base class.
Topic: Ruby Advanced Features
Description: There are some advanced Ruby development techniques, such as BEGIN and END blocks, defining modules, defining modules, the use of threads, and how to handle exceptions. There are also some Ruby-specific dynamic language features.
BEGIN and END blocks
In Java, there are the concepts of "prenotification" and "postnotification", where the so-called "prenotification" is the execution of the module before loading, and the "postnotification" is the execution of the module before loading, and the "postnotification" is the execution of the module before loading. The so-called "prenotification" is the module executed before loading, and "postnotification" is the block of code after the execution of the main code.
The Ruby language uses BEGIN and END blocks to implement the "prenotification" and "postnotification" operations. BEGIN is the initialization of the registration, and END is the end of the registration, which is executed when the interpreter releases the file.
BEGIN{
# Initialization code
# Initialization code.
}
END{
# Release code
}
Topic: Modules
Description: A module is similar to a class in that it is a set of methods and constants. Unlike classes, modules do not have instances, but it is possible to add a module's momentum to know the class or a specified object.
Defining Modules
Use the module keyword
module moduleName
The module body
end
Instance variables, instance methods, class variables, class methods and attributes can be defined in a module just like in a class, and classes and modules can also be defined in a module. Similarly modules can be defined in classes.
Tip: If you define an internal module in a module, you can access the nested module in the same format as you access the internal class, i.e., in the form of "external module::internal module".
Namespaces
Namespaces can be implemented in Ruby using modules to prevent naming conflicts.
You instantiate a class inside a module using "module name::class name" and then call the class instance methods.
Although you can use internal classes to implement namespaces in Ruby, you rarely use them in applications; instead, you use modules as namespaces.
Loading external files
In large applications, different classes or modules are often stored in different files. Ruby provides four methods for loading external files: load, require, include, and extend.
The load method
The load method is used to load a source file with a ".rb" extension, which requires the full filename to be used when loading the file. load is actually a copy and paste method. Once the Ruby source file is loaded using the load method, you can use the Ruby code written in the source file directly in your program. As follows:
load "system.rb";
The require method
As with the load method, source files can be loaded using the require method, which is more powerful in that it can load not only Ruby source files, but also source files written in other languages.
require "common/console.c".
The include method
The include method is mainly used to insert () amount can be said to include) a module into a class or other modules. include method usage:
1> introduce a module in the class definition, so that the methods in the module become instance methods of the class.
2> Introduce module in class definition, want to introduce both instance methods and class methods, this time you need to use include method. But the definition of the class method in the module is different, the definition appears in the method def self.include(c).... . end.
The extend method
The extend method is used to introduce a module into an object so that the class has the module's methods. Typically, the extend method is used to introduce a module into a class definition and to make the methods in the module class methods.
Topic: Threads
Description: A thread is the smallest unit of program execution, used to complete a single sequentially controlled process. Running multiple threads simultaneously in each program to accomplish different jobs becomes multithreading, the advantages of which are high portability, concurrent execution, and shared memory space. The disadvantage is that its execution efficiency is lower than that of a process.
Creating Threads
User-level threads in Ruby depend on the operating system. They accomplish certain tasks and also change with the operating system. Threads must be created before they can be used, and the way to do this is as simple as creating an instance of the Thread class. The syntax format is as follows:
thread = Thread.new do
as the block in which the thread executes
End
Note: Threads can also be created using Thread.start, an alias of Thread.new, which has exactly the same syntactic effect.
When creating a thread, you can also pass parameters to the thread and then get the parameters in the thread block and process them accordingly.
Note: When more than one thread exists in a Ruby program, they will execute alternately, or concurrently.
Returning to the Current Thread
You can return to the currently running thread in Ruby by calling the current method of the Thread class.
Hanging the current thread
In Ruby, you can call the join method of the Thread class to suspend the current thread until the specified thread is executed, and then execute the suspended thread.
Note: If the thread finishes executing without being joined, it will be an error to join the thread.
You can also hang the current thread by using the thread's value method, which is different from the join method in that the value method gets the value of the thread.
Pause Threads
The pass method of the THread class allows you to pause a thread and execute another thread. Unlike the Thread method described earlier, the pass method is a class method of the Thread class, so it needs to be called using the Thread.pass form.
Stopping a Thread
To stop a thread you can use the exit method of the Thread class or the kill method, which will exit the thread completely when you stop it.
Tip: In a thread, if you stop the main thread using the exit method or the kill method, the program will exit.
Sleeping a thread
Use the sleep method to hibernate the current thread for a period of time. Once the time has expired, the thread will automatically change from a dormant state to an executable state.The Ruby language also allows you to set a thread to sleep using the stop method, and to wake up the specified thread using the wakeup method.
Getting Thread Status
In Ruby, once a thread is created, it can have multiple states during execution. To get the current status of a thread, use the status method in Thread.
sleep The thread is in a sleep state, or waiting for IO. run The thread is running. run The thread is running. Thread is running. aborting The thread has been aborted. false The thread is terminated normally. false Thread terminated normally nil nil Thread aborted
The Thread class also contains an alive? method for determining whether a thread can be executed. The priority of a thread can also be viewed and modified using priority.
Exception Handling
The Ruby language can also handle various exceptions at program runtime. When an application encounters an exception, it "throws" an exception and terminates the current method until it finds an exception to handle and the stack is cleared.
Common Exceptions
Exception Name Common Reason Thrown RuntimeError RuntimeError Default exception thrown by raise method raise NoMehodError NoMehodError Thrown by calling a non-existing method. NoMehodError Thrown by calling a non-existing method > > Exception message stu=Object.new new NameError The interpreter has encountered an error that cannot be resolved.
An identifier for a variable or method name stu.UnknownMethodName
Exception message thrown if a=some_random_identifier
IOError When reading closed streams and writing read-only
Exception thrown when reading a closed stream, writing a read-only > > or similar operation
Message STDN.puts("Cannot write to stream")
Errorno:error A set of errors related to file IO File.Open(-l)
TypeError when passing unprocessable parameters to a method
Exception information thrown a=10+"string"
ArgunmentError thrown when an error occurs in the number of arguments passed to def foo
Exception message method body
end
foo(1,2,3)
catch exception
Use rescue statements and ensure statements to catch exceptions in Ruby. The rescue statement is used to jump out of the program from exceptions, provided that the program needs to be contained in BEGIN and END blocks; the ensure statement is used to handle the processing after the exception occurs, such as the recovery of system resources.
Throw exception manually
The rescue statement captures and handles exceptions. The syntax format of the raise statement is as follows:
raise the name of the exception class, exception message string
Manually thrown exceptions can also be caught using rescue
Custom exception class
In addition to several built-in exceptions, Ruby also allows developers to customize exception classes. To create a custom exception class, you need to inherit from the Exception class.
Topic: Other Dynamic Language Features
Explanation: Ruby not only has the safety and strong type features of object-oriented languages such as C# and Java, but also has the flexibility of scripting languages such as JavaScript and Perl. For example, when calling an undefined method, the error handling callback method is automatically called.
method_missingmethod
In Ruby, if a method of a class or an instance is called, and the system does not search for the method, the method_missing method will be called.
Proc method
Proc (procedure) objects are used to bind a set of local variables to a block of code. Once bound, the code can be called in different online Aiwen environments.
Dynamically execute code
The so-called dynamic execution of code means that without knowing in advance what statements are to be executed or not anticipating all possible situations, parameters or certain codes are passed from other places to perform the tasks to be completed.
Dynamically executing code using eval is slightly slower than normal execution, so use eval with caution. Don't use it too frequently.
garbage collector
The garbage collector is an important part of modern software virtual machine technology. Interpreter languages such as Java, Python, C#, and Ruby all use garbage collection for memory management. Ruby provides the GC class and ObjectSpace class to provide garbage collection functionality.
The GC class has only four methods: disable, enable, start and garbage_collect. The function of the first two is to close and start the garbage collector. The start method and the garbage_collect method have the same meaning, and they both implement the garbage collection function.