The object model of Ruby learning

Source: Internet
Author: User

This two weeks work more content, usually oneself also a bit not in the state, learn something a little, take advantage of now still a bit state, hurriedly review before study of Ruby Bar.

Ruby was the first language that I really started to touch the dynamics of language, though it was used and always used in scripting languages such as Perl and Python, but just as an extension of the Unix shell (and work-related), without really looking at the philosophy of dynamic language. Is the "Ruby Meta-Programming" this book, as if to open a new world to me the door, the book introduced in each of the characteristics of the excitement I almost jumped up, this is the charm of learning it.

A probe into Ruby language

Because it's the first Ruby essay, let's start with a brief introduction to Ruby's grammar rules. Ruby's syntax is a bit similar to Python, but does not require strict indentation (and of course no special case indentation is required), so the end keyword is used to indicate the ending.

To tell you the truth, you haven't delved into each of the variable types in Ruby, but one thing is certain: dynamic, strongly typed. The so-called strong type is a variable can only one type, can not be changed to other types, and in practice, you will find that a variable is free and implicit conversion, such as

Var=1

Var= "string"

There is no problem, but that does not mean that Ruby is a weakly typed language. Like Python, a variable in Ruby is actually a reference to memory, and when the type of a variable is implicitly changed, a new piece of memory is created, and the variable name points to the new address as a reference to the new value, and the old memory content when his reference count becomes 0. will be collected in a timely manner by the system's garbage collection mechanism. (here with Python's memory principle analogy, and did not prove, if there are errors, I hope that everyone put forward)

Ruby starts with a lowercase or underscore keyword as the variable name, starts with @ as the instance variable name, defines the class with the Classes keyword, the module keyword definition block, the DEF keyword definition method, the Initialize method constructs an object, the return keyword returns a value, Using the. Call method and so on, without any very strange syntax, everything seems so natural.

Objects in Ruby

Ruby is full of objects, each of which comes from a class, and this class may inherit from a parent class. An object can also be called an instance of a class, a property of an object, that is, an instance variable of a class, stored in an object, and a method of an object, that is, an instance method of a class, stored in a class. So different instances under the same class can share methods, but instance variables are not shared. Each class inherits from the object class, which holds methods such as Class () (the class that looks at the object), and object inherits from the Basicobject class (The Whiteboard class, which creates objects that inherit the confession Board class to eliminate any previously possible methods). Each object's class is Class,class just a module that encapsulates methods such as new () ...

It is a bit of a mouthful, I have a rough picture (the solid line represents class, the dashed lines represent superclass):

Methods in Ruby

When you invoke the method of an object, the system looks for the method from the class of the object, and if it is not found, then finds it in the parent class in the previous level until the method is found, and if it is not found, it calls the Method_missing () method, invokes the Ghost method, or reports the message that called the error. You can call the Ancestors method to view the ancestor chain of the current object (that is, the chain structure of the above lookup process, especially after object, to find the kernel module, because object contains the kernel module, kernel contains methods such as print), Ruby is looking for methods on the ancestor chain in turn.

After finding the method, it is natural to execute, however, according to the above, the method's search needs to go through an ancestor chain, then how to determine the recipient when invoking this method? In Ruby, each line of code executes in the current object, which is self, and the method that does not explicitly specify the recipient is raised on self.

In fact, when each Ruby script executes, a main object is created as the current object, and self is the main (main is also called the top-level context, as in Python's shelf code, rather than the concept of the entry function in c,c++).

Private methods in Ruby are also different from C + +. The method after the Private keyword can only be called by an implied receiver (and because when the method is called, if the recipient is not himself, you must explicitly specify a recipient, the underlined text above) so the private method can only be called by itself. Check if the private method call is legitimate, just check whether the recipient (no) is specified and who the current self is.

Extension: In Ruby, there is an evil way to get any rule waiver to access any method, including private, which is the Send method.

Class operations in Ruby

In Ruby, a class is defined with the class keyword, and if the class does not exist, the class is created, and if the class exists, methods, properties, and so on, are added to the existing class. This operation is also valid for the class that comes with it. As an example in a book, remove other symbols of non-letters, numbers, and spaces in the string. Think of a method that is handled with a regular expression:

def to_alphanumeric (s)

? ? S.gsub/^\w\s/, "

End

In Ruby, you can "open" the String class and add the method directly in the class:

Class String

? ? def to_alphanumeric

? ? ? ? Gsub/^\s\w/, "

? ? End

End

So there is a new method to_alphanumeric in the string.

PS: This is the first time I know that there is a way to define this, which makes me feel fresh, like opening a window and all the new scenery out there.

The "Open" class adds a method that looks cool, but when you think about it, there is a problem: if the To_alphanumeric method already exists in the string, then the call is not sure which method to call. (By the time I wrote this essay, I didn't quite know how to implement C + + in Ruby, or what it would look like with override)

Constants and modules in Ruby

Like Python, it starts with a capital letter to represent a constant. Constants are only valid at the current scope, similar to the structure of a directory tree, and the same name constants under other scopes are irrelevant, like files of the same name under different directories.

From the beginning of the essay, module is the superclass of class, in fact module is a collection of some instance methods, and class is a module (such as the new () method) that encapsulates several functions. Module is very similar to class, but it is quite different, and when it needs to be inherited or instantiated, it should use the class (superclass () method and the new () method), and when it needs to be contained (include, import) elsewhere, Modules should be used.

Modules are like directories, and different constants (methods or attributes) in a module can be viewed as files, constants, and modules that form a structure similar to a file tree, and are called with double colons to represent the path (::). The concept of a namespace is defined by the way in which the path can be displayed uniquely to the position of the constant.

The object model of Ruby learning

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.