In `s = :x`, `s` is a local variable identifier; `:x` is a Symbol object. An identifier is a name Ruby uses for a program element. Recognizing its form helps you tell variables, constants, keywords, and method names apart—but the form alone does not always settle what a bare word means. section 1.1.3 section 8.2.2
Variable prefixes provide a quick first clue:
- A local variable starts with a lowercase letter or underscore; `first_name` follows the usual underscore convention, while `firstName` is valid but unconventional. section 1.1.3
- An instance variable starts with `@`, as in `@age`. It holds information in an individual object. section 1.1.3
- A class variable starts with `@@`, as in `@@running_total`; a global variable starts with `$`, as in `$population`. Some predefined globals have punctuation or digits after `$`. section 1.1.3
Table 1.4 Valid variable names in Ruby by variable type
| Type |
Ruby convention |
Nonconventional |
|---|---|---|
| Local |
|
|
| Instance |
|
|
| Class |
|
|
| Global |
|
|
Compare conventional variable names with valid but unconventional spellings across the four variable types. section 1.1.3
A bare word needs more interpretation. Ruby first recognizes reserved keywords such as `def` and `if`. An identifier followed by `=` is a local variable being assigned; one followed by parentheses, such as `x()`, is a method call. Otherwise, Ruby resolves it against existing local variables and methods. An unresolved `x` raises an error that mentions both possibilities: Ruby cannot know which one you intended. section 2.5.4
A name is not its Symbol object
Try `s = :x`, then `abc = 1` and `Symbol.all_symbols.grep(/abc/)` in irb. Ruby records names used for variables, methods, and constants in an internal symbol table; the name `abc` can appear there as `:abc`. That does not make the identifier `abc` and the Symbol object `:abc` interchangeable. Avoid testing whether a symbol existed earlier by writing `Symbol.all_symbols.include?(:abc)`: writing `:abc` itself enters it in the table. section 8.2.2
A name’s meaning also depends on where it appears. Local, global, and class variables have different scope rules; constants have resolution rules of their own. Instance variables belong to the current `self` rather than to a local scope. When a name seems to refer to the wrong thing, check both its identifier type and the surrounding scope or `self`. section 5.2 section 5.5




