Explain the single-piece method and single-piece class in Ruby, and explain the ruby single-piece Method

Source: Internet
Author: User

Explain the single-piece method and single-piece class in Ruby, and explain the ruby single-piece Method

Single-piece Method

Ruby allows adding methods to a single object. This method takes effect only for a single object. It is called a single-piece method.

Sample Code

str = “just a regular string”def str.title?  self.upcase == selfendstr.title? # => falsestr.methods.grep(/title?/) # => [:title?]str.singleton_methods  #=> [:title?]str.class # => StringString.title? #=> NoMethodError

In addition to the preceding definition method, you can also use the Object # define_singleton_method method to define a single-piece method.

Single-piece methods and class methods

In the previous notes, classes in Ruby are also objects, while class names are constants. Therefore, calling methods on classes is actually the same as calling methods on objects:

The essence of a class method is: it is a single-piece method of a class. In fact, if we compare the definition of a single-piece method with that of a class method, we will find that the two are actually the same.
 

def obj.a_singleton_method; enddef MyClass.another_class_method; end

Both use the def keyword for definition.

Def object. method # method subject end

The above object can be * object reference, constant class name, or self.

Attr_accessor

Ruby objects have no attributes. If you want to get something like attributes, You need to define a read method and a write method (that is, set and get methods in java and objc) respectively ), the most direct method is as follows:

Sample Code

class MyClass  def my_attribute=(value)    @my_attribute =value    end  def my_attribute    @my_attribute  endendobj = MyClass.newobj.my_attribute = ‘x'obj.my_attribute  #=> ‘x'

However, in the preceding method, if there are many attributes, there will be a Repeat Yourself, and the following three macros can be used:

  • Module # attr_reader generates a read Method
  • Module # attr_writer generates a write Method
  • Module # attr_accessor simultaneously generates read and write Methods

Sample Code

class MyClass  attr_accessor :my_attribueend

Is this much more concise? Of course, the usage (read and write) is consistent with the above implementation.

Single-piece class

We know that the search order of object methods in Ruby is: first to the right and then up. The meaning is to first find the class of the object to the right and first try to find it in the instance method of the class, if not, continue to search for the ancestor chain.

The previous article introduced the single-piece method. A single-piece method is a method that is only valid for an object. If a single-piece method is defined for an object, what is the search order of this single-piece method?

class MyClass  def my_method; endendobj = MyClass.newdef obj.my_singleton_method; end

First, the single-piece method will not be in obj, because obj is not a class, and it is not in MyClass. In this case, all myclasses should be able to share and call this method, it cannot create a single-piece class. Similarly, the single-piece method cannot be in a position of the ancestor chain (similar to superclass: Object. The correct position is in the single-piece class. This class is actually when we ask the object for its class in irb (obj. class), the difference is that this class is slightly different from ordinary classes. It can also be called a metadata class or an intrinsic class.

Open a single-piece class

Ruby provides two methods to obtain single-piece class references. One is to use the traditional keyword class with special syntax.

Method 1
 

Class <an_object # your own code endobj = Object. newsingleton_class = class <obj selfendsingleton_class.class # => Class

Another method is to use the Object # singleton_class method to obtain the reference of a single-piece class:

Method 2

“abc”.singleton_class  # => #<Class: #<String:0xxxxxx>>

 
Features of single-piece classes

  • Each single-piece class has only one instance (known as the reason for a single-piece class) and cannot be inherited.
  • A single-piece class is the survival of a single-piece method of an object.
  • Method Search after a single-piece class is introduced

Based on the basic understanding of single-piece classes, after introducing single-piece classes, Ruby's Method Search should not start with its class (common class, instead, we should first start searching from the single-piece class of the object. If the desired method is not found in the single-piece class, it will start along the class (common class, then go to the ancestor chain to find. In this way, from the beginning of a single-piece class, everything goes back to the order when we didn't introduce a single-piece class.

You can verify it by using the following code:

class C  def a_method    ‘C#a_method()'  endendclass D < C; endobj = D.new

Open a single-piece class and define a single-piece Method

class << obj  def a_singleton_method    ‘obj#a_singleton_method()'  endendobj.singleton_class.superclass #=> D

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.