Ruby real variables

Source: Internet
Author: User

A real variable starts with @ and Its range is limited to the self object. two different objects can have real variables with different values even if they belong to the same class. from outside the object, real variables cannot be changed or even observed (for example, Ruby's real variables are never public), unless the Method ProgramLike a global variable, the value of the real variable before the initialization is nil.

Ruby real variables do not need to be declared. This implies the elastic Structure of the object. In fact, every real variable is dynamically added to the object when it first appears.

Ruby> class insttest
| Def set_foo (N)
| @ Foo = N
| End
| Def set_bar (N)
| @ Bar = N
| End
| End
Nil
Ruby> I = insttest. New
# <Insttest: 0x83678>
Ruby> I. set_foo (2)
2
Ruby> I
# <Insttest: 0x83678 @ Foo = 2>
Ruby> I. set_bar (4)
4
Ruby> I
# <Insttest: 0x83678 @ Foo = 2, @ bar = 4>

Note that the value of @ bar is not reported until the set_bar method I is called in the previous example.

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.