Programming ruby-class variables and class methods

Source: Internet
Author: User
Tags uppercase letter

Class variables and class methods
For a long time, all classes we created contain instance variables and instance methods: variables and methods associated with a specific class instance.
Sometimes, classes also need to have their own States. So there is a class variable.
Class variable
Class variables are shared among all objects of the class and can be accessed by class methods described later. A specific class variable has only one copy in a given class.
The class variable name starts with two "at" symbols, for example, @ count. Unlike global variables and instance variables, class variables must be initialized before use.
In general, initialization only defines a simple value assignment within the class.
For example, the player wants to record the playback times of each song. When playing a song, this value increases in the instance.
But we still want to know how many songs have been played. We can query all the song instances and add their counts or
Use a global variable to avoid the risk of good design. Instead, we use a class variable.

 Code 
Class Song
@ Plays = 0
Def Initialize (name, artist, duration)
@ Name = Name
@ Artist = Artist
@ Duration = Duration
@ Plays = 0
End
Def Play
@ Plays + = 1 # Same as @ plays = @ plays + 1
@ Plays + = 1
" This song: # @ plays. Total # @ plays. "
End
End

For debugging purposes, I specifically return a string containing the number of times the song was played and the total number of times all the songs were played during song # play.
Let's perform a simple test.

 Code 
S1 = Song. New ( " Song1 " , " Artist1 " , 234 ) # Test songs ..
S2 = Song. New ( " Song2 " , " Artist2 " , 345 )
S1.play -> " This song: 1 plays. Total 1 plays. "
S2.play -> " This song: 1 plays. Total 2 plays. "
S1.play -> " This song: 2 plays. Total 3 plays. "
S1.play -> " This song: 3 plays. Total 4 plays. "

Class variables are private to the class and its instances. If you want to make them accessible, you need to write an accesser method.
This method can be an instance method or a class method we will mention below.

Class Method
Sometimes classes need to provide methods that are not bound to a specific instance. We have used this method.
This new method creates a new song object, but it is not associated with a specific song.

 
  Song=Song. New (.)

 

 
 

You can find the shadows of class methods in the ruby class library. For example, a file object corresponds to a file opened in a file system.
However, the file class also provides many class objects to operate files that are not opened, so there is no file object.
If you want to delete a file, you can call file. Delete to input the file name.

  File. Delete ("Doomed.txt")

 

 
 

The class file is distinguished from the instance method by definition. The class method name is defined as adding the class name and point before the method name.

  Code   
code highlighting produced by actipro codehighlighter (freeware)
http://www.CodeHighlighter.com/
--> class example
def instance_method # instance method
end
def example. class_method # class method
end
end

The automatic phonograph is billed by song instead of by time. The use of short songs has a high profit. We want to prevent the songs in the playlist from being too long.
We can define a class method in the playlist to check whether a specific song is out of the range. We use a class constant to set this range,
This is a simple constant (remember a constant? They start with an uppercase letter) and are initialized in the class.

 Code 
Class Songlist
Max_time = 5 * 60 # 5 minutes
Def Songlist. is_too_long (Song)
Return Song. Duration > Max_time
End
End
Song1 = Song. New ( " Bicylops " , " Fleck " , 260 )
Songlist. is_too_long (song1) -> False
Song2 = Song. New ( " The calling " , " Santana " , 468 )
Songlist. is_too_long (song2) -> True

 

Singleton mode and other structures
Sometimes you want to override the default method for Ruby to create objects. For example, we use an automatic player. Because we have many automatic changers distributed across the country,
We want to maintain them as easy as possible. One requirement is to record all events that occur on the automatic PLAYER: playing a song and receiving a payment,
Strange data streams. Because we want to keep the network bandwidth of music, we will save these record files locally.
That is to say, we need a class to process these records. However, we want each player to have only one record object,
We also hope that this record object can be used by other objects. This is the singleton mode. We sorted out these things, so the only way to create record objects
Is to call mylogger. Create, we will ensure that only one record object will be created forever.

Code
ClassMylogger
Private_class_method: New
@ Logger=Nil
DefMylogger. Create
@ Logger=New unless @ Logger
@ Logger
End
End

By making the new method of mylogger private, we block and use this constructor to create record objects.
Instead, we provide a class method mylogger. Create. This method is saved using the class variable @ Logger
The reference of a single logger instance. This instance is returned every time this method is called.
We test it by viewing the identifier returned by this method.

Code
Mylogger. Create. ID-> 936550
Mylogger. Create. ID-> 936550

 

Using the class method as a pseudo constructor makes it easier for users of your class. For example, a shape class that describes a polygon.
A shape instance is created using a given constructor. It requires two parameters: edge number and perimeter.

Code
ClassShape
DefInitialize (num_sides, perimeter)
#
End
End

However, over the past few years, this class has been used in different applications.Program, This program creates a graph by name and the length of one side, rather than the perimeter.
Simply add some class methods to the shape.

 Code  
code highlighting produced by actipro codehighlighter (freeware)
http://www.CodeHighlighter.com/
--> class shape
def shape. triangle (side_length)
shape. new ( 3 , side_length * 3 )
end
def shape. square (side_length)
shape. new ( 4 , side_length * 4 )
end

class methods have many interesting and powerful applications, but discovering them won't let our automatic changers do it earlier, so let's continue.

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.