Attribute is a very useful propety in Ruby.It like the 'get/set' method in Java and the 'property' in C#,but it is easier and more useful than these language.For example,in Java language you need write too codes like these:
class A{
private int a;
public int getA(){
return a;
}
public void setA(int a){
this.a = a;
}
....
}
And you see,there are too many codes.In C#,it may be easyer than java,but you need write more code,too.
In Ruby,you can write 'get method' codes like the following:
attr_reader :name
then,if there are many instance variables which need be read,you can write following:
attr_reader :name,:artist,:duration
Use ',' to separate these variables(Note:remember that there is a space between the 'reader' word and the ':').
The 'set' method is like
attr_writer :name,:artist,:duration
And the 'get/set' method:
attr_accessor :name,:artist,:duration
Now,you can see why I say that the Attribute in Ruby is easier.And you will know why I say that the Attribute in Ruby is more useful in the next part which I reference from <pragmatic.programmers.programming.ruby.2nd>:
These attribute-accessing methods do not have to be just simple wrappers around an
object¡¯s instance variables. For example, you may want to access the duration in minutes
and fractions of a minute, rather than in seconds as we¡¯ve been doing.
</pragmatic.programmers.programming.ruby.2nd>
ruby 代码
- class Song
- def duration_in_minutes
- @duration/60.0
- 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¡¯ve used attribute methods to create a virtual instance variable. To the outside
world, duration_in_minutes seems to be an attribute like any other. Internally,
though, it has no corresponding instance variable.
This is more than a curiosity. In his landmark book Object-Oriented Software Construction
[Mey97], Bertrand Meyer calls this the Uniform Access Principle. By hiding
the difference between instance variables and calculated values, you are shielding the
rest of the world from the implementation of your class. You¡¯re free to change how
things work in the future without impacting the millions of lines of code that use your
class. This is a big win.
Note:there is a '=' when you define the
Virtual Attribute between the name of attribute and the argument
ruby 代码
- def duration_in_minutes=(new_duration)