Last active
December 13, 2015 23:28
-
-
Save cookrn/4991608 to your computer and use it in GitHub Desktop.
Ruby Variable Types
- Local
- Instance
- Class
- Constant
- Pseudo-global
- Global
- Local variables live within a scope
- Useful for referencing values that are only needed within a scope
- Useful for setting temporary values in methods or other places
- Start with a lowercase letter and no symbols e.g. var
# local variable
x = 1
# even though we're scoped inside of a proc
# we can still access x since it was defined in
# a higher scope
proc { puts x }.() # 1
class Dummy
def hi
y = 2
end
def there
puts y
end
end
d = Dummy.new
d.hi
d.there # NameError
- Instance variables are tied to the instance scope they are created in
- Everything in Ruby is an object and therefore an instance of something
- Useful for tracking values for the lifetime of an object
- Start with an @ sign e.g. @var / @Var / @VAR
class Business
attr_reader :name
def initialize( name )
@name = name
end
end
b = Business.new "ACME Inc."
b.name # "ACME Inc."
- Class variables are tied to the class scope they are created in
- Class variables are shared with and inherited by ancestor classes
- Not the reverse though!
- Useful for tracking data at the class level
- Typically not idiomatic ruby to use class vars
- Usually use instance variables at the class level -- no weird inheritance issues
- Start with two @s e.g. @@var / @@Var / @@VAR
class Business
@@a = "word"
@c = "word1"
def self.hi
puts @@a
end
hi # "word"
def self.test
puts @@b
end
test # NameError
end
class SuperBusiness < Business
puts @@a # "word"
@@b = "other"
puts @c
@c = :word2
test # "other"
end
- Static values tied to the class scope they are created in
- Will receive warnings and errors attempting to change the value of a constant
- Visible in ancestors
- Class and Module names are constants
- Start with a capital letter and have no symbols except underscores
class Business
ATTRIBUTES = [ :name , :address ]
end
class SuperBusiness < Business
end
Business::ATTRIBUTES
SuperBusiness::ATTRIBUTES
- Result of Regex matches
- Result of forked processes
- Cannot set them on your own!
- Only the runtime sets them
- Look like globals but are thread local(?)
- Start with $ e.g. $1 / $2 /
$3 / $ @ / $$
"abc123" =~ /(\d+)\z/
puts $1
- Accessible throughout the runtime including other processes and threads
- Not idiomatic to use them!
- Start with $ e.g. $stdout / $var / $Var / $VAR
$var = 1
fork do
puts $var # 1
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment