The real world is full of objects. We can classify them. for example, when a very small child sees a dog, no matter what type it is, they will be called "bow-wow". We are born to have the ability to understand the world by type.
In terms of OO programming, a class of objects like "dog" is called a class, and some special objects belonging to this class are called the instance of that class ).
Generally, to create an object in Ruby or other OO languages, you must first define the class attributes and then create an object. to illustrate this, let's first define a simple Dog class.
Ruby> class Dog
| Def speak
| Print "Bow Wow \ n"
| End
| End
Nil
In Ruby, a class is defined as a piece of code between the key class and the end. def in the field begins to define a method of the class (we have discussed it in the previous section), which corresponds to some specific object methods in this class.
Since we already have the Dog class, we can use it to create a Dog:
Ruby> pochi = Dog. new
# <Dog: 0xbcb90>
We have completed a brand new entity of the Dog class and named it pochi. the new method of any class creates a new entity. because pochi is a Dog that corresponds to the defined class, it has all the attributes of the defined Dog. because our idea of Dog is really simple, we can only let pochi play a trick.
Ruby> pochi. speak
Bow Wow
Nil
Creating a new kind of entity is also called instantiating. We need to tease a real Dog, instead of making the Dog class speak to us.
Ruby> Dog. speak
ERR: (eval): 1: undefined method 'speak' for Dog: class
Eating "sandwich concept" is obviously meaningless.
At the same time, if we only want to hear the call of a dog without any emotion, we can create (materialized) a short-lived, temporary dog and scream a few bits before it disappears.
Ruby> (Dog. new). speak # or more commonly, Dog. new. speak
Bow Wow
Nil
"Wait," you said. "Where did this poor guy disappear? "Well, if we don't mind giving it a name (just like giving it to pochi earlier), Ruby's automatic garbage collector will think it's a stray dog, and then it will be processed relentlessly. this is indeed feasible, you know, because we can create any dog at will.