Variable Type | Naming Rule (Start) | Naming Rule (Characters) | Scope |
---|---|---|---|
Local Variable | Lowercase letter or _ | Alphanumeric or _ | Valid only inside methods or blocks |
Global Variable | $ | Alphanumeric or _ | Accessible from anywhere |
Class Variable | @@ | Alphanumeric or _ | Accessible from all instances of the class |
Instance Variable | @ | Alphanumeric or _ | Accessible within the instance |
Constant | Uppercase letter | Alphanumeric or _ | Accessible in the same way in both instance and class methods |
Valid only inside methods or blocks.
You must assign a value to a local variable with =
before referencing it.
takada = "Local variable, come out!"
def sengen
takada
end
p sengen
Traceback (most recent call last):
1: from exam.rb:5:in `<main>'
exam.rb:3:in `sengen': undefined local variable or method `takada' for main:Object (NameError)
# takada is not declared, so this is an error
def sengen
takada = "Local variable, come out!"
end
p sengen
"Local variable, come out!"
Accessible from anywhere. Generally, global variables should be avoided.
$takada = "Global variable, come out!"
def sengen
$takada
end
p sengen
"Global variable, come out!"
Shared in both class methods and instance methods, and also shared between superclasses and subclasses.
class Takada
@@sakebu = 'Class variable, come out!'
def self.sakebu
@@sakebu
end
def initialize(sakebu)
@@sakebu = sakebu
end
def sakebu
@@sakebu
end
end
class Koriki < Takada
@@sakebu = 'Not angry!'
def self.sakebu
@@sakebu
end
end
p Takada.sakebu
p Koriki.sakebu
"Not angry!"
"Not angry!"
Takada should shout “Class variable, come out!”, but when the Koriki class is defined, @@sakebu is changed to “Not angry!”.
If you use a class instance variable instead, the result is different.
class Takada
@sakebu = 'Class variable, come out!'
def self.sakebu
@sakebu
end
def initialize(sakebu)
@sakebu = sakebu
end
def sakebu
@sakebu
end
end
class Koriki < Takada
@sakebu = 'Not angry!'
def self.sakebu
@sakebu
end
end
p Takada.sakebu
p Koriki.sakebu
"Class variable, come out!"
"Not angry!"
Accessible within the instance.
Accessible in the same way in both instance and class methods.
Reference