Ruby Object-Oriented Programming learning note, ruby object-oriented

Source: Internet
Author: User

Ruby Object-Oriented Programming learning note, ruby object-oriented

Open Class

You can re-open an existing class and modify it dynamically, even if the class of a standard library such as String or Array is no exception. This behavior is called open class)

Monkey patch

If you carelessly add new functions for a class and overwrite the original functions of the class, and then affect the code of other parts, such patches are called Monkeypatch)

Classes and modules

The class keyword of Ruby 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, and the class is an enhancement module with three methods (new, allocate, superclass). These three methods can be used to organize the class inheritance structure and create objects.

The concepts of classes and modules in Ruby are very similar, and they can be replaced by each other. The reason why both classes and modules are retained is to keep the code clear and make the code intent clearer. Usage principles:

  • To include your code to other codes, use the module
  • If you want a code to be instantiated or inherited, you should use the class
  • The module mechanism can be used to implement Namespace concepts similar to those in other languages.

IN Ruby: Symbol

The path (scope) of constants in Ruby is similar to the directory in the file system. It is divided and accessed through:. By default, it starts with: (for example: Y) the root location of the variable path.

What is an object?

An object is a group of instance variables plus a reference pointing to its class. The object method does not exist in the object itself, but in the object class.

What is a class?

A Class is an object (an instance of the Class) plus a group of instance methods and a reference to its superclass. A Class is a subclass of the Module Class, so a Class is also a Module.

Differences between load and require methods

Both load and require can be used to import other people's code. The difference is that the load method is used to load the Code. If you do not want to pollute the current namespace, You need to load ('file. rb ', true) explicitly requires the creation of an anonymous module to take over the file. the constant of rb. require is used to import the class library. In addition, the load method will run the loaded file again each time it is called. require will load each library file only once.

Prepend, include and ancestor chain

The ancestor chain is used to describe the inheritance relationship of Ruby objects. Because classes and modules are parent-child relationships, the ancestor chain can also contain modules. prepend and include can respectively add modules to the chain, the difference is that when the include method is called, the module will be inserted into the ancestor chain, the current class is on the top, and the prepend is also inserted into the ancestor chain, but the other positions are on the front and bottom of the current class, in addition. ancestors can view the current ancestor chain

Private rules

Private methods cannot be called by explicitly specifying recipients. Private methods can only be called by implicit receiver self (Object # send is an exception)

Self-related

When a method is called, the receiver will assume the self Role and define a module (or class) for any method call that does not explicitly specify the receiver, this module (or class) assumes the self role.

Relationship between objects, classes, and modules

The above Module. class points to the Class. It can be understood that the content in the above box is Class, but their parent-child relationship is established through superclass and has similarities and differences, which can be viewed through class. ancestors.

Dynamic Method

Dynamic call Method

In Ruby, the Object # send method can replace the vertex ID to call the specified instance method of the Object.

Sample Code
 

class MyClass  def my_method(my_arg)    my_arg * 2  endendobj = MyClass.newobj.my_method(3)  #=> 6obj.send(:my_method, 3) #=> 6

The above code gets the same result through direct calling and using the send method call. The advantage of using send is that the method call can be dynamically determined in encoding. This technique is called dynamic dispatch in metaprogramming.

In addition, you must note that Object # send can call both public methods and private methods of objects. If you want to retain the encapsulation feature of the Object and do not expose the private Method to the outside, you can use the Object # public_send method.

Dynamic definition method

In addition to dynamic call of methods, Ruby also provides a dynamic method definition method through the Module # define_method method and code block.

Sample Code

class MyClass  define_method :my_method do |my_arg|    my_arg * 3  doendobj = MyClass.newobj.my_method(2) #=> 6

The above code replaces the keyword def through the define_method method, which is essentially the same, but in terms of the definition method, the define_method method is more flexible and can be deduced in encoding, the function definition increases implementation flexibility.

Method_missing Method

Strictly speaking, the method_missing method is not clearly defined (it will not appear in the methods list ), in essence, it intercepts the call information through the Method Search Mechanism and then gives a reasonable response to the corresponding method. It is similar to throwing an exception in exception handling.

Method_missing uses the mechanism that when an object calls a method, it searches for the instance method of its corresponding class. If no method is found, it searches up along the ancestor chain, until the BasicObject class is found. If none of them exist, a BasicObject # method_missing is finally called to throw a NoMethodError exception.

When we need to define many similar methods, we can rewrite the method_missing method to respond to similar methods in a unified manner, so that the behavior is similar to the call of the defined method.

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(10) + 1   puts "#{number}..."  end  "#{person} got a #{number}" endendnumber_of = Roulette.newputs number_of.bobputs number_of.kitty

Dynamic proxy

For encapsulated objects, call is collected by using the method_missing method, and these calls are forwarded to the encapsulated object. This process is called a dynamic proxy, where method_missing reflects the dynamic, forwarding reflects proxy

Const_missing Method

Similar to method_missing, there is also the const_missing Method for constants. When a non-existent constant is referenced, Ruby will pass this constant name as a symbol to the const_missing method.

Whiteboard (blank slates)

A whiteboard class has very few methods. by inheriting the BasicObject class, you can quickly obtain a whiteboard class. In addition to this method, you can also delete a common class into a whiteboard class.

Delete Method

There are two ways to delete a method:

  • Module # undef_method
  • Module # remove_method

The difference between the two is that Module # undef_method deletes all (including inherited) methods. While Module # remove_method only deletes the method of the receiver, and retains the inherited method.

Dynamic Methods and usage principles of Method_missing

Use dynamic methods whenever possible. Unless you must use the method_missing method (in case of many methods), use it as little as possible.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.