Learning notes on object-oriented programming in Ruby

Time:2021-12-24

Open class

You can reopen existing classes and dynamically modify them, even classes in standard libraries such as string or array. This behavior is called an open class

monkey patch

If you carelessly add new functions to a class, cover the original functions of the class, and then affect other parts of the code, such a patch is called monkey patch

Classes and modules

RubyThe class keyword is more like a scope operator than a type declaration statement. The core task of the class keyword is to bring you to the context of the class so that you can define methods in it.

Each class is a module. A class is an enhanced module with three methods (new, allocate, superclass). These three methods can organize the inheritance structure of the class and create objects

The concepts of class and module in ruby are very similar, and they can completely replace each other. The reason why they are retained at the same time is to maintain the clarity of the code and make the intention of the code more clear. Use principle:

  • If you want to include your own code into other code, you should use modules
  • If you want a piece of code to be instantiated or inherited, you should use class
  • The module mechanism can be used to implement namespace concepts similar to those in other languages

: symbol in Ruby

The path (SCOPE) of the constant in ruby is similar to the directory in the file system. It is divided and accessed through::. By default, it directly starts with:: (for example::: y) to represent 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 method of the object does not exist in the object itself, but in the class of the object.

What is a class

A class is an object (an instance of a class) plus a set of instance methods and a reference to its superclass. Class is a subclass of module class, so a class is also a module.

Similarities and differences between load and require methods

You can import other people’s code through load and require. The difference is that the load method is used to load the code. If you don’t want to pollute the current namespace, you need to create an anonymous module through the explicit request of load (‘File. RB ‘, true) to take over the file RB constant, require is used to import the class library. In addition, each call of the load method will run the loaded file again according to the loading times, and require will load each library file only once.

Prepend, include and ancestral chain

Ancestor chain is used to describe the inheritance relationship of ruby objects. Because classes and modules are parent-child relationships, modules can also be included in the ancestor chain. Prepend and include can add modules to the chain respectively. The difference is that by calling the include method, the module will be inserted into the ancestor chain directly above the current class, while prepend is also inserted into the ancestor chain, However, other positions are directly below the current class. In addition, class The ancestors can view the current ancestor chain

Private rule

Private methods cannot be called by explicitly specifying the recipient. Private methods can only be called through the implicit receiver self (object#send is an exception)

Self correlation

When a method is called, the receiver will play the role of self. Any method call that does not explicitly specify the receiver is regarded as the method calling self. When a module (or class) is defined, the module (or class) will play the role of self

Relationship between objects, classes and modules

Learning notes on object-oriented programming in Ruby

Module Class also refers to class. It can be understood that the contents of the above boxes are all class, but their parent-child organization relationship is established through superclass and there are similarities and differences. You can use class View the data from the managers.

Dynamic method

Dynamic call method

In ruby, the object #send method can replace the point identification to call the specified instance method of the object

Sample code
 

?
1
2
3
4
5
6
7
8
9
class MyClass
  def my_method(my_arg)
    my_arg * 2
  end
end
 
obj = MyClass.new
obj.my_method(3#=> 6
obj.send(:my_method, 3) #=> 6

The above code obtains the same result through direct call and using send method call. The advantage of using send is that the method call can be determined dynamically in coding. This technique is in yuanprogrammingIt is called dynamic distribution

In addition, it should be pointed out that not only public methods but also private methods of objects can be called through object #send. If you want to preserve the encapsulation characteristics of the object and do not expose private methods, you can use object#public_ Send method.

Dynamic definition method

In addition to the dynamic invocation of methods, ruby also uses module #define_ Method methods and code blocks provide a way to define dynamic methods

Sample code

?
1
2
3
4
5
6
7
8
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 is defined by_ The method method replaces the keyword def, which is essentially the same, but in the definition method, define_ Method is more flexible. You can define functions through derivation in coding, which increases the flexibility of implementation.

method_ Missing method

Strictly speaking, method_ Missing method is not a clear definition (it will not appear in the methods list). Its essence is to intercept the call information through the method search mechanism, and then give a reasonable response to the corresponding method. It is a bit similar to throwing exceptions in exception handling, throwing them out layer by layer.

method_ Missing uses the mechanism that when an object makes a method call, it will look up the instance method of its corresponding class. If it is not found, it will look up along the ancestor chain until the basicobject class is found. If none, a basicobject#method will eventually be called_ Missing throws a nomethoderror exception.

When we need to define many similar methods, we can override the method_ Missing method, which uniformly responds to similar methods, so that its behavior is similar to calling the defined methods.

Sample code

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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(10) + 1
   puts "#{number}..."
  end
  "#{person} got a #{number}"
 end
end
 
number_of = Roulette.new
puts number_of.bob
puts number_of.kitty

Dynamic agent

For some encapsulated objects, use method_ The missing method collects calls and forwards them to the encapsulated object. This process is called dynamic proxy, where method_ Missing embodies dynamic and forwarding embodies proxy

const_ Missing method

And method_ Similar to missing, there is const about constants_ Missing method. When referring to a nonexistent constant, ruby will pass the constant name as a symbol to const_ Missing method.

Blank slates

Classes with few methods are called whiteboard classes. By inheriting the basicobject class, you can quickly get a whiteboard class. In addition to this method, you can also change a common class into a whiteboard class by deleting the method.

Delete method

There are two ways to delete a method:

  • Module#undef_method
  • Module#remove_method

The difference between the two is module #undef_ Method will delete all (including inherited) methods. Module #remove_ Method only deletes the recipient’s own method and retains the inherited method.

Dynamic method and method_ Usage principle of missing

When dynamic methods can be used, try to use dynamic methods. Unless method must be used_ Missing method (especially when there are many methods), otherwise use it as little as possible.

Recommended Today

The Kafka tools tool is more convenient to use

2. Installation Download the corresponding version according to different systems. The Kafka version here is 1.1.0, and download Kafka tool 2.0.1. Double click the downloaded exe icon to complete the installation. 3. Simple use For Kafka environment construction, please refer to:CentOS7. 5. Build kafka2 11-1.1.0 cluster 1) Connect Kafka Open the Kafka tool installation directory […]