Programming ruby-objects, attributes, and methods

Source: Internet
Author: User

Objects and attributes
The song object we created has an internal State (such as song title and artist ). This state is private to other objects-other objects cannot access the instance variables of an object. Generally, this is a good thing. This ensures object consistency.
However, a fully closed object is useless-you can create it, but cannot use it. You usually define some methods for you to call or operate the object state, and use the object to interact with the external world. These visible parts are called attributes. For our song object, the first thing we need to do is to view its title and artist (so that we can display them when playing the song) and playback time (we can display it in the progress bar ).

 Code 
Class Song
Def Name
@ Name
End
Def Artist
@ Artist
End
Def Duration
@ Duration
End
End
Song = Song. New ( " Bicylops " , " Fleck " , 260 )
Song. Artist -> " Fleck "
Song. Name -> " Bicylops "
Song. Duration -> 260

 

Here we define three accessors to return three instance variables. For example, the method name () returns the instance variable @ name. Because this is a general style, Ruby provides a quick way: attr_reader creates these accessors for you.

 Code 
Class Song
Attr_reader: name,: artist,: Duration
End
Song = Song. New ( " Bicylops " , " Fleck " , 260 )
Song. Artist -> " Fleck "
Song. Name -> " Bicylops "
Song. Duration -> 260

 

This example introduces some new things. This structure: artist is an expression that returns a symbolic object equivalent to artist. You can think like this: artist is the name of the variable artist, and artist is the value of this variable. In this example, the accessors are named name, And the instance variables @ name, @ artist, and @ duration corresponding to artist and duration are automatically created. The methods of these accessors are the same as what we wrote earlier.

Writable attributes
Sometimes you need to be able to set attribute values through external objects. For example, let's assume that the playing time associated with the song is an estimated value (probably the information collected from CD or mp3) during initialization ). When we play a song for the first time, we can get its actual length, and then save the new value to this song object.
In C ++ and Java languages, you can use the setter method.

Code
ClassJavasong {//Java code
Private duration _ duration;
Public void setduration (duration newduration ){
_ Duration=Newduration;
}
}
S=New Song (.);
S. setduration (length );

 

In Ruby, attributes of an object can be accessed like other variables. For example, song. Name. Therefore, it seems natural that you will assign these values to these variables when setting values for attributes. In Ruby, you create a method that adds an equal sign after the name. These methods can be used as containers for value assignment.

Code 
Class Song
Def Duration = (New_duration)
@ Duration = New_duration
End
End
Song = Song. New ( " Bicylops " , " Fleck " , 260 )
Song. Duration -> 260
Song. Duration = 257 # Set attribute with updated value
Song. Duration -> 257

 

This value of song. Duration = 257 will execute the duration = method in the Song object and input the parameter 257. Similarly, Ruby provides a quick method for creating simple property settings.

 Code 
ClassSong
Attr_writer: Duration
End
Song=Song. New ("Bicylops","Fleck",260)
Song. Duration= 257

 

Attribute Essence
These attribute access methods do not simply encapsulate the instance variables of an object. For example, you may want to obtain the playback time in units rather than in seconds.

 Code 
Class Song
Def Duration_in_minutes
@ Duration / 60.0 # Force floating point
End
Def Duration_in_minutes = (New_duration)
@ Duration = (New_duration * 60 ). To_ I
End
End
Song = Song. New ( " Bicylops " , " Fleck " , 260 )
Song. duration_in_minutes -> 4.33333333333333
Song. duration_in_minutes = 4.2
Song. Duration -> 252

 

Here we use the attribute method to create a real instance variable.
In the external view, duration_in_minutes is like other attributes. Internally, it does not have corresponding instance variables.

Attributes, instance variables, and methods
Attribute descriptions may make you think they are no different from methods -- why do we need another name? To some extent, this is true. Attribute is a method. Sometimes the attribute simply returns the value of an instance variable. Sometimes a calculation result is returned for the attribute. Sometimes these strange methods with equal signs after the names are used to update the state of an object. Therefore, the question is when to use attributes and how to use them? What is the difference between properties and methods? In the end, this is just a question of "angels on a pinhead. This is entirely based on individual needs.

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.