Ruby and Metaprogramming are objects of all things _ruby topics

Source: Internet
Author: User
Tags anonymous instance method object model shallow copy

Opening

Empty is the color, and the color is empty.
Empty and empty, in the Ruby language, everything is an object.

Ruby is an object-oriented language (object oriented Language), and the object-oriented concept is much more robust than other languages.

The raw type data and object type data in Java are not present in Ruby. Most of the stuff in Ruby is an object.

So, to master the metaprogramming of Ruby and Ruby, the object is the first compulsory lesson. This is the time to focus on the objects in Ruby.

Objects in Ruby

If you turn from other object-oriented languages, one can think of creating a class and then creating an instance of the class to produce an object.

This is entirely possible in Ruby, but the process of first building a class to get an object sounds more like a class-oriented design than an object-oriented design. Some things about the class put it next time.

In Ruby, there is no concept of the original type, 1, 0.3, true/false, or even nil are objects. For example, you can try the following code in IRB:

Copy Code code as follows:

>> 1.methods
=> ["%", "odd", "inspect", "prec_i", "<<", "tap", "div", "&", "Clone", ">>", "Public_methods", "__send __ "," instance_variable_defined? "," equal "," freeze "," To_sym "," * "," ord "," LCM "," + "," extend "," next "," power! "," Send "," Round "," methods ", <...more methods...>" Is_a? "," Ceil "," [] "]
>> 1.class
=> Fixnum

You can try other data types in IRB, look at their methods and classes, and so on.

More than just a variety of data types, methods are also objects in Ruby, such as the following examples:

Copy Code code as follows:

>> One_plus = 1.method (: +)
=> #<method:fixnum#+>
>> One_plus.class
=> method
>> One_plus.call (2)
=> 3

Interestingly, the method object also has a method:

Copy Code code as follows:

>> one_plus.arity ()
=> 1

What exactly is the object?

What exactly is an object?

Simply put, * * object is state + behavior * *

State is the attribute that indicates the current object has, and each homogeneous object may have a different state, which is saved in the instance variable (Instance Variable).

An instance variable of an object can be set/read by Instance_variable_set/instance_variable_get:

Copy Code code as follows:

>> 1.instance_variable_set (: @my_var, "World")
=> "World"
>> 1.instance_variable_get (: @my_var)
=> "World"

Behavioral behavior is the action on the object, is the way we often say. The invocation of a Ruby method, similar to Smalltalk or OBJECTIV-C, takes message mode. Calling a method is equivalent to sending a message to this object. So a call to a method can do the same:

In Ruby, the state, which is the instance variable, is stored in the object, and the behavior or method is inside the object's class or Mixin module.

In a static language, compile-time determines whether the invoked method exists, and no compilation errors occur.

In Ruby, when we run the method call, the object finds the class, module, parent class, etc., to find the corresponding method.

Singleton/meta/anonymous/ghost/shadow Class

1.Singleton Class: Single Case class
2.Meta class: Meta class
3.Anonymous class: Anonymous classes
4.Ghost class: Ghost Class
5.Shadow Class: Shadow Class

The above stuff is actually said to be a thing, I like to call it shadow class.

Each object in Ruby is a shadow class that exists between the object and the class to which it belongs:

Object ("Obj1")-> the Class (String) to which the Shadow class-> object belongs

When a method of an object is invoked, the shadow class is first searched, and then the class to which it belongs.

As mentioned above, the instance variable exists within the object, and the method exists in the object's class.
A method on a shadow class is one that only the object has. This method is often referred to as a single instance method (Singleton).

Such a method exists only on this object, and other objects of the same class do not have this method, because their shadow classes are different, and there is no such method on the shadow classes of other objects.

Copy Code code as follows:

>> a = "obj1"
=> "Obj1"
>> def A.hello
>> puts "Hello World"
>> End
=> Nil
>> A.hello
Hello World
=> Nil
>> B = "Obj2"
=> "Obj2"
>> B.hello
nomethoderror:undefined method ' Hello ' for ' obj2 ': String
From (IRB): 49
>> A.singleton_methods
=> ["Hello"]
>> B.singleton_methods
=> []

Self

Everything in Ruby is an object, and self is also an object, specifically a reference to the current object.

The preceding article says that Ruby's method invocation is a message pattern, such as Obj.method, where the recipient of the message is. Previous objects,. After the method and parameters.
If the object and. Do not appear, the message is sent to the Self object by default. Self is also the resolution object of an instance variable, except as the default recipient of a method.

Self was set to be an object called main at the beginning of Ruby, and then IRB could see:

Copy Code code as follows:

>> m = Self
=> Main

Self can be considered a special variable, and its particularity is that you cannot assign him a value:
Copy Code code as follows:

>> self = "obj"
Syntaxerror:compile Error
(IRB): 77:can ' t change the value of self
Self = "obj"
^

There are several ways to change the value of self. (Obj.method.) is one of them, except. There is also the Class/module keyword.
The main focus of this return is related to the object.

When we call a method with Obj.method, the next time code executes into the appropriate method, the running context switches to that object, and self naturally becomes that object. When you define a single case method with Def, the truth is also interlinked. The following example illustrates the case of the self switching.

Copy Code code as follows:

>> a = "obj"
=> "obj"
>> def a.hello_self
>> puts "Hello #{self}"
>> End
>> m = Self
=> Main
>> a.hello_self
Hello obj

Replication of objects

It is said that the existence of the object consists of two parts, one is the state/instance variable, the other is the behavior, and this paper focuses on the singleton method and the Shadow class.
There are also two modes of copying objects in Ruby, one of which is to copy only the current state/instance variable DUP. The other is copied together with the Shadow class and the referenced object, thus copying a single instance method.

Copy Code code as follows:

>> a = "obj"
>> def a.hello_self
>> puts "Hello #{self}"
>> End
>> B = a.dup
=> "obj"
>> b.hello_self
nomethoderror:undefined method ' hello_self ' for ' obj ': String
From (IRB): 90
>> B = A.clone
=> "obj"
>> b.hello_self
Hello obj

In fact, these features, even without class,ruby, can be used as a prototype (JavaScript-like) object-oriented language.

You can create an object, generate a default instance variable, set the behavior as a singleton method on the object's shadow class, and then use clone to generate thousands of instances. Of course this is more troublesome, but it is one of the feasible ways.

Other Object APIs

Objects also have many other functions, such as freeze, and DUP and clone have some other reference to the above differences, DUP only copy the reference, the clone bar refers to the object also copied.

These can be found on the object class (all Ruby object's parent classes) API, and you can view apidock.com documents

For example, about DUP

DUP () produces a shallow copy of Obj-the instance variables of obj are copied, but not the objects they. DUP copies the tainted state of obj. Also the discussion under Object#clone. In general, clone and DUP could have different semantics in descendant classes. While clone was used to duplicate a object, including its internal state, DUP typically uses the class of the descendant O Bject to create the new instance.

Ben back to the end

This back tells you something about objects, some basics, some of the features of Ruby itself.

One of the two most characteristic features of the Ruby object model is the shadow class/single example method and self, and it is best to understand these two concepts in depth.

And listen to let's.

Next time, focus on some kind of story.

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.