What is an accessor?
We've discussed the real variables before, but not too much discussion. The real variable of an object belongs to its property and is a general difference from other objects from the same class. It is important to read and write its properties; This requires a property accessor (attribute accessors) Approach. We will soon see that we do not always have to explicitly write accessor methods, but let us now understand all the details. The two types of accessors are write (writer) and read (reader).
Ruby> class Fruit
| def set_kind (k) # a writer
| @kind = k
| end
| def get_kind # a Reader
| @kind c6/>| End
|
Nil
ruby> f1 = fruit.new #<fruit:0xfd7e7c8c> ruby> f1.set_kind
("Peach") # Use the writer
' Peach '
ruby> f1.get_kind # Use the reader
' peach ' ruby> F1
# Inspect the OBJEC T
#<fruit:0xfd7e7c8c @kind = "Peach" >
Simple enough; We have access to information about the kind of fruit we're searching for. But our method name is still a little grumbling. The following is simpler and more convenient.
Ruby> class Fruit
| def kind= (k)
| @kind = k
| end
| def kind
| @kind
| end
| end
nil
ruby> f2 = fruit.new
#<fruit:0xfd7e7c8c> ruby> f2.kind
= "banana"
"banana"
ruby> f2.kind
"Banana"