Ruby constant Parsing

Source: Internet
Author: User

A constant starts with an uppercase letter. it should be assigned a maximum of once. in the current Ruby version, a constant value assignment only generates warnings rather than errors (non-ANSI eval. RB will not report this warning)

Ruby> fluid = 30
30
Ruby> fluid = 31
31
Ruby> Solid = 32
32
Ruby> Solid = 33
(Eval): 1: Warning: already initialized constant solid
33

Constants can be defined in the class, but unlike real variables, they can be accessed outside the class.

Ruby> class constclass
| C1 = 1, 101
| C2= 102
| C3= 103
| Def show
| Print C1, "", C2, "", C3, "\ n"
| End
| End
Nil
Ruby> C1
Err: (eval): 1: uninitialized constant C1
Ruby> constclass: C1
101
Ruby> constclass. New. Show
101 102 103
Nil

Constants can also be defined in the module.

Ruby> module constmodule
| C1 = 101
| C2 = 102
| C3 = 103
| def showconstants
| print C1, "", C2, "", C3, "\ n"
| End
nil
Ruby> C1
err: (eval): 1: uninitialized constant C1
Ruby> include constmodule
Object
Ruby> C1
101
Ruby> showconstants
101 102 103
Nil
Ruby> C1 = 99 # Not really a good idea
99
Ruby> C1
99
Ruby> constmodule:: C1 # the module's constant is undisturbed...
101
Ruby> constmodule: C1 = 99
err: (eval): 1: Compile error
(eval): 1: parse error
constmodule: C1 = 99
^
Ruby> constmodule: C1 #.. regardless of how we tamper with it.
101

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.