Skip to content

Instantly share code, notes, and snippets.

@koriroys
Created February 20, 2014 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koriroys/9122675 to your computer and use it in GitHub Desktop.
Save koriroys/9122675 to your computer and use it in GitHub Desktop.
Ruby Scoping
#####################
# CONDITIONALS
#####################
def variables_in_passing_conditionals
special_string = "Awesome!"
if true
result = "You win!"
end
"#{result}, #{special_string}"
end
variables_in_passing_conditionals
#####################
# CONDITIONALS
#####################
def variables_in_failing_conditionals
special_string = "Awesome!"
if false
result = "You win!"
end
"#{result}, #{special_string}"
end
variables_in_failing_conditionals
#####################
# GLOBAL
#####################
def testing_scope_global_variable(num)
$a << num
end
$a = [1, 2]
testing_scope_global_variable(2)
$a
#####################
# CONSTANTS
#####################
MAX_AGE = 22
def working_with_constants
"the max age for a student is: #{MAX_AGE}"
end
working_with_constants
MAX_AGE
##############################
# CONSTANT SPECIFIC NAMESPACE
##############################
def working_with_constants
"the max age for a student is: #{Stuff::Max_age}"
end
module Stuff
Max_age = 22
end
working_with_constants
#####################
# DYNAMIC CONSTANTS
#####################
MAX_AGE = 42
def working_with_constants
MAX_AGE = 22
"the max age for a student is: #{MAX_AGE}"
end
working_with_constants
MAX_AGE
############################
# CHANGING A CONSTANT
############################
MAX_AGE = 22
def working_with_constants
"the max age for a student is: #{MAX_AGE}"
end
working_with_constants
MAX_AGE = 99
working_with_constants
#####################
# LOCAL SCOPE
#####################
def testing_scope_local_variable(num)
a = []
a << num
end
a = [1, 2]
testing_scope_local_variable(2)
a
#####################
# INTERNAL ITERATORS
#####################
def variables_with_loops
1.upto(10) do |num|
number = num
end
number
end
variables_with_loops
#####################
# EXTERNAL ITERATORS
#####################
def variables_with_for_loops
for num in (1..10)
number = num
end
number
end
variables_with_for_loops
@0xqd
Copy link

0xqd commented Oct 14, 2014

the weird part about constant in Rails is it can be changed. If you are in Rails, you can use CONSTANT = 'something'.freeze

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment