Open Class
You can reopen a class that already exists and modify it dynamically, even if the class of a standard library like string or array is no exception. This behavior is called Open class
Monkey Patch
If you inadvertently add new functionality to a class, overwriting the original functionality of the class, and then affecting other parts of the code, this patch called the Monkey Patch (Monkeypatch)
Classes and modules
Ruby's class keyword is more like a scoping operator than a type declaration statement. The core task of the Class keyword is to take you to the context of the class so that you can define the method inside.
Each class is a module, and the class is an enhanced module with three methods (New,allocate,superclass), through which you can organize the class's inheritance structure and create objects
The concepts of classes and modules in Ruby are very close to each other, and the reason for preserving both is to keep the code clear and to make the code more explicit. Principle of Use:
- If you want to include your code in other code, you should use the module
- You want a piece of code to be instantiated or inherited, you should use a class
- Modular mechanisms can be used to implement namespaces (Namespace) concepts similar to those in other languages
Ruby:: Symbol
The path (scope) of a constant in Ruby, similar to a directory in the file system, is split and accessed by default directly to:: Opening (example::, Y) representing the root position of the variable path
What is an object
An object is a set of instance variables plus a reference to its class. The object's method does not exist in the object itself, but in the object's class.
What is a class
A class is an object (an instance of the Class) plus a set of instance methods and a reference to its superclass. A class class is a subclass of a module class, so one is also a module.
The similarities and differences of load and require methods
You can import other people's code through both load and require, and the Load method is used to load code, and if you do not want to pollute the current namespace, you need to create an anonymous module with the explicit requirements of load (' file.rb ', true). A constant that takes over the FILE.RB, require is used to import the class library, and in addition, the Load method runs the loaded file every time it is loaded, and require loads only once for each library file.
Prepend, include and ancestor chains
Ancestor chains are used to describe the inheritance relationships of Ruby objects, because classes and modules are parent-child relationships, so the ancestor chain can also contain modules, prepend and include can add modules to the chain, respectively, by invoking the Include method, the module being inserted into the ancestor chain, the current class directly above, The prepend is also inserted into the ancestor chain, but the rest of the position is just below the current class, and the current ancestor chain can be viewed through class.ancestors
Private rule
Private methods cannot be invoked by explicitly specifying the recipient. Private methods can only be invoked through the recessive recipient self (object#send is an exception)
Self related
When a method is invoked, the recipient acts as the self role. Any method call that does not explicitly specify the recipient is defined as a module (or Class) when the method is invoked to call self, and the module (or Class) plays the self role
Relationships between objects, classes, and modules
The above Module.class point is also class classes, you can understand that the above box is class, but their parent-child relationship through superclass established and similarities and differences can be viewed through class.ancestors.
Dynamic method
Dynamic Invocation Method
In Ruby, a Object#send method can be used instead of a point identifier to invoke a specified instance method of an object
Sample code
Class MyClass
def my_method (my_arg)
My_arg * 2
end
obj = myclass.new
obj.my_method (3) #=> 6
obj.send (: My_method, 3) #=> 6
The code above is the same as the result of directly calling and using the Send method call, and the advantage of using send is that the method invocation can be dynamically determined in the encoding. This technique is called dynamic distribution in metaprogramming
Another point to note is that you can call not only public methods but also private methods of an object by Object#send. If you want to preserve the encapsulation attributes of an object, you can use the Object#public_send method without exposing the private method externally.
Dynamic Definition Method
In addition to the dynamic invocation of the method, Ruby also provides a dynamic method definition by Module#define_method methods and blocks of code
Sample code
Class MyClass
Define_method:my_method do |my_arg|
My_arg * 3 do end
obj = myclass.new
obj.my_method (2) #=> 6
The above code replaces the keyword def by the Define_method method, which is essentially the same, but in terms of definition, the Define_method is more flexible, and the flexibility of implementation can be increased by deducing and completing the definition of the function in code.
Method_missing method
In a strict sense, the Method_missing method is not a definite definition (it will not appear in the methods list), its essence is to intercept the call information by means of the mechanism of the method lookup, and then to give a reasonable response to the corresponding method. A bit similar to exception handling in the thrown exception, one layer to the outside throw.
The mechanism used by method_missing is that when an object makes a method call, it looks in the instance method of its corresponding class and, if not found, looks up the ancestor chain until the Basicobject class is found. If none, a basicobject#method_missing is eventually invoked to throw the Nomethoderror exception.
When we need to define many similar methods, we can respond to similar methods by overriding the Method_missing method, so that the behavior is similar to the method defined by the call.
Sample code
Class Roulette
def method_missing (name, *args) person
= name.to_s.capitalize
super unless%w[bob Frank Bill Honda eric].include? Person number
= 0
3.times do number
= rand (a) + 1
puts "#{number} ..." End
"#{person} got a #{num ber} "end end
number_of = roulette.new
puts Number_of.bob
puts Number_of.kitty
Dynamic Proxy
For some encapsulated objects, the call is collected through the Method_missing method and forwarded to the encapsulated object, this process is called dynamic Proxy, in which method_missing embodies the dynamic, forwarding embodies the agent
Const_missing method
Like Method_missing, there is a const_missing method for constants, and when you reference a nonexistent constant, Ruby passes the constant name as a symbol to the Const_missing method.
Whiteboard class (blank slates)
A class with very few methods is called a Whiteboard class, and by inheriting the Basicobject class, you can quickly get a whiteboard class. In addition to this method, you can change a normal class to a whiteboard by deleting the method.
Delete method
There are two ways to delete a method:
- Module#undef_method
- Module#remove_method
The difference is that Module#undef_method deletes all (including inherited) methods. Instead, the Module#remove_method deletes only the recipient's own methods and retains the inherited methods.
The principle of using dynamic method and method_missing
When you can use dynamic methods, use dynamic methods whenever possible. Use it sparingly unless you have to use the Method_missing method (especially in a very different way).