Introduction to the use of classes for Ruby organization objects

Source: Internet
Author: User
Tags constant instance method readable ticket

Classes and instances

September 5, 2016 7:35 * * *

A class defines methods, and the reason for class existence is to be instantiated, that is, to create an instance of a class to get an object. An instantiated action, like this:

obj = object.new
Object is a class that is built into Ruby, using a dot form on a class, which is the point between object and new. You just send a message to the class. Class responds to this information just as an object can respond to information. Class is also an object. The new method is a constructor, which is a method within a class that can be machined and returned to a new instance.

You can use class keywords to define classes, and the names of classes are constants, starting with uppercase letters. Constants can store information, and constant values can be changed, but you can't assign a new value to a constant so Ruby warns you. The best approach is to avoid assigning new values to constants that already have values.

To create a Ticket class, which has a simple method:

Class Ticket
Def event
' Can not really to be specified yet ... '
End
End
Now you can create a new ticket object, and then ask the event:

Ticket = Ticket.new
Puts Ticket.event
Invoking method Ticket.event executes the event method and outputs the output in this method:

Can not really be specified yet ...
In the example above we created and executed an instance method.

7:47 * * * *

Instance method

Before we defined a method directly above an object, this is done:

def ticket.event
Just now we define the event method in the Ticket class:

Def event
The method defined in the class appears on all instances of this class, which is the instance method (instance methods). They do not belong to just one object, and all instances can call them.

The method we define above a particular object is called an independent method (singleton methods), such as Def Ticket.price. An object has a price method that does not care whether the method is an independent or an instance method, but as a programmer we should know the difference.

7:54 * * * *

Overlay method

7:54 * * * *

The method is defined in the class, and we can redefine it again, in the following example, the method of two times M is repeated:

Class C
def m
Puts ' first definition method M '
End

def m
Puts ' second definition method m '
End
End
Take a look at what happens when we call M on an instance of C:

c.new.m
The result of the output is "second definition method M", and the second definition wins because what we see is the output of the second definition of the M method. When we cover a method, the new version will win.

8:02 * * *

Re-open Class

8:02 * * *

In most cases, when you define a class, you create a block of class definitions:

Class C
# Here's the code for the class
End
Re-open this class to add additional items or modifications can be done. Like this:

Class C
def X
End
End

Class C
Def y
End
End
We open the definition body of the class, add an X method, and turn off the definition body. We then reopen the definition body, add a second method Y, and then turn off the definition body. This is the same effect as the following:

Class C
def X
End

Def y
End
End
8:07 * * * *

instance variables vs. Object state

8:09 * * * *

The information and data associated with an object is the state of the object. We need to do this:

Sets and resets the state of an object (a ticket says you spent 10 bucks)
Read back status (Ask a ticket, how much do you need to pay?) )
The instance variable (instance variables) is the mechanism for storing and retrieving values used by Ruby objects. Instance variables allow each individual object to remember their state. Instance variables are similar to other variables, you assign values to them, you can read them back, you can add them together, output them, and so on. But there are a few different places:

The name of the instance variable begins with the @ sign, which makes it easy to know which is the instance variable.
Instance variables can only be used internally by the object to which they belong.
Initializes an instance variable within a method inside a class that can be used in any method of a class.
Take a look at an example:

Class Person
def set_name (String)
Puts ' Set name ... '
@name = string
End

def get_name
Puts ' returns the name ... '
@name
End
End

Joe = Person.new
Joe.set_name (' Joe ')
Puts Joe.get_name
When calling the Set_name method we assign an instance variable in this method, the name is @name, and the variable can also be used in other methods in the class, for example, we use a @name instance variable in the Get_name method.

8:25 * * * *

Initializing an object with state

8:27 * * * *

In a class you can define a method whose name is initialize, and this method is automatically invoked each time a new instance is created. Take a look at an example:

Class Ticket
DEF initialize
Puts ' Create a new ticket '
End
End
When you call Ticket.new, you will see a "Create a new ticket" message appear.

You can use this automatic initialization method to set the state in the object when creating the object. For example, when you want to create a ticket to have the ticket to have the venue (venue) and date of the two states, you can make them the values of the arguments when you create them, and the values of those parameters are passed to the Initialize method so that you can save the values of those parameters as instance variables:

Class Ticket
def initialize (venue,date)
@venue = Venue
@date = Date
End
Before you close the block that defines the class, do something else by adding a way to read back the venue and date values. Continue to add the following code:

def venue
@venue
End

def date
@date
End
End
The two methods use instance variables, and they are the last expression in the method, which is the value returned by the method.

8:40 * * * *

The Setup method

8:51 * * *

The way to sign the name

Class Ticket
def initialize (Venue,date,price)
@venue = Venue
@date = Date
@price = Price
End

def Price
@price
End
End

The initialization method can become very long, and we have to remember the order of the parameters. Can be improved, for example, we use a Set_price method, can be used to set or reset the price of tickets, so change:

Class Ticket
def initialize (Venue,date,price)
@venue = Venue
@date = Date
End

def set_price (amount)
@price = Amount
End

def Price
@price
End
End
The above Set_price can also be written like this:

def price= (amount)
@price = Amount
End
The method ends with the = number, which can be used when you use it:

Ticket.price= (63.00)
or use it directly:

Ticket.price = 63.00
The above is actually a call to a method, but it looks like an assigned expression. This form is syntactic sugar, which denotes the use of a special rule.

9:32 * * * *

Attribute and attr* Method family

September 6, 2016 7:38 * * *

Attribute and property translated into Chinese can be "attributes." The value of a property can be read and written by an object. For example, we have seen the object of the ticket, each ticket has a price,date,venue attribute. Price= This method can be considered as a method of writing attributes, Date,venue, and the methods used by the read properties of price. Write/read with Get/set is a meaning.

Automatically create properties

Take another look at the previous code:

Class Ticket
Def initialize (venue, date)
@venue = Venue
@date = Date
End

def price= (Price)
@price = Price
End

def venue
@venue
End

def date
@date
End

def Price
@price
End
End
In terms of reading and writing of attributes, there is a read/write property (price) and two read properties (venue and date). It can be done like this, but it's a little repetitive, like the three forms of the method:

def something
@something
End
Ruby provides a way to automatically create read and return instance variable values, like this:

Class Ticket
Attr_reader:venue,:d ate,:p rice
End
There are a few things that start with a colon, these are symbols (symbols), symbols are named or marked with something. Explain the difference between it and the string later.

Self is the default recipient

You see some of the calling methods without obvious recipients, such as when calling Attr_reader. In this case, the information is sent to self, which is the default object. At the top level of the body that defines the class, self is the class object itself, that is, the object that accepts Attr_reader information is actually Ticket.

There's a Attr_writer method, like this:

Class Ticket
Attr_writer:p Rice
End
Then use these two attr_* methods to improve the Ticket class:

Class Ticket
Attr_reader:venue,:d ate,:p rice
Attr_writer:p Rice

Def initialize (venue, date)
@venue = Venue
@date = Date
End
End
Such a ticket object will have Venue,date,price properties, Venue,date is a readable property, and price is a readable and writable property.

941e615e-5ecf-4567-8217-ddd888f33de5

To create a read-write property with Attr_accessor

You can use Attr_accessor to create a read and write method for a property. It's equivalent to Attr_reader plus attr_writer.

Class Ticket
Attr_reader:venue,:d ate.
Attr_accessor:p Rice
#.. etc.
End
There is also a attr, this use:

attr:p Rice, true
The second argument true indicates the use of Read and write methods.

Summary of attr* method

Attr_reader

Code:
Attr_reader:p Rice

Equivalent:
def Price
@price
End
Attr_writer

Code:
Attr_writer:p Rice

Equivalent:
def price= (Price)
@price = Price
End
Attr_accessor

Code:
Attr_accessor:p Rice

Equivalent:
def price= (Price)
@price = Price
End

def Price
@price
End
attr

Code:
# the equivalent of Attr_reader
attr:p Rice

# the equivalent of Attr_accessor
attr:p Rice, true
8:26 * * *

Inherited

9:00 * * *

Inheritance is a relationship between two classes, and a class inherits some behavior from another class (Subclass,superclass). Looking at an example, Magazine inherits publication, and Magazine is the subclass,publication of the publication class Magazine:

Class publication
Attr_accessor:p ublisher
End

Class Magazine < Publication
Attr_accessor:editor
End
Magzine inherited the use of a < symbol, it is a subclass, it inherits the publication class, this class for magzine this class is a superclass.

Do an experiment:

Mag = magazine.new
Mag.publisher = ' ninghao.net '
Mag.editor = ' John '
Puts ' #{mag.publisher} is the publisher of the magazine, and #{mag.editor} is the editor of the magazine.
Because the Magzine class inherits the publication class, the Magzine object also contains the properties and methods inside the publication.

We can continue:

Class Ezine < Magzine
End
This Ezine object will have Publisher and editor properties. Each Ruby class can inherit only one class.

Do an experiment:

Class C
End

Class D < C
End

Puts D.superclass
Puts D.superclass.superclass
The output is:

C
Object
C is the superclass,object of D is the superclass of C.

9:12 * * *

Classes as objects and recipients of information

9:12 * * *

A class is a special object that is the only object that can be born. Create a class, such as Ticket, where you can send information to it, add methods to it, and pass it as a parameter of the method to other objects, and you can handle the class object as you would any other object.

To create a class object

All of them, such as Object,person,ticket, are instances of class. Use class keywords to create a class object:

Class Ticket
# code
End
Creating a Class object using the above method is easy to read and you can also create class objects like this:

My_class = Class.new
The class object created above can create its own instance:

Instance_of_my_class = My_class.new
If you want to use Class.new to create an anonymous class, and you want to add an instance method to it when you create it, you can add a code block after class.new, like this:

c = class.new do
def Say_hello
Puts ' Hello '
End
End
10:17 * * * *

The nature and nurture of Ruby objects

Is_a? Method can tell you whether an instance belongs to a class, or the ancestor class of the class to which it belongs:

>> mag = magazine.new
=> #
>> mag.is_a? (Magazine)
=> true
>> mag.is_a? (publication)
=> true
An instance is not entirely affected by the class to which it belongs, and you can add a method for a separate instance object, such as letting magzine grow wings:

Mag = magazine.new
def mag.wings
Puts ' I can fly! '
End
Mag.wings
Constant

10:17 * * * *

The name of a constant begins with a capital letter. The names of classes are constants, and constants are often used in classes to hold important data.

An example:

Class Ticket
venues = ["Convention Center", "fairgrounds", "Town Hall"]
If you want each ticket to come from a site defined in venues, you can do so in the Initialize method of the class:

Def initialize (venue, date)
If Venues.include? (venue)
@venue = Venue
Else
Raise Argumenterror, "Unknown venue #{venue}"
End
@date = Date
End
You can use a double colon to get the value of a constant outside of the definition class:

Class Ticket
venues = ["Convention Center", "fairgrounds", "Town Hall"]
End

Puts Ticket::venues
Predefined Constants for Ruby

>> Math::P i
=> 3.141592653589793
>> ruby_version
=> "2.3.1"
>> Ruby_patchlevel
=> 112
>> ruby_release_date
=> "2016-04-26"
>> ruby_revision
=> 54768
>> Ruby_copyright
=> "Ruby-copyright (C) 1993-2016 Yukihiro Matsumoto"
>>
Reassigning and modifying constants

To reassign a value to a constant that has already been assigned a value, you receive a warning from Ruby and try:

>> A = 1
=> 1
>> A = 2
(IRB): 36:warning:already initialized constant A
(IRB): 35:warning:previous definition of A is here
=> 2
But you can modify the value of a constant:
Venues = Ticket:venues
Venues << ' Gymnasium '

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.