The concept of Ruby accessor

Source: Internet
Author: User

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"

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.