Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@sk187
Created March 27, 2015 15:19
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 sk187/a2d1e525243b57aa45f3 to your computer and use it in GitHub Desktop.
Save sk187/a2d1e525243b57aa45f3 to your computer and use it in GitHub Desktop.
Ruby Variable Scope
# Global
class Scope
$global = "I am a global variable"
@@class_variable = "I am a class variable"
def initialize(instance_variable)
@instance_variable = instance_variable
end
def instance_message
@instance_variable
end
def self.class_message
@@class_variable
end
end
# Creating a new instance of the Scope class called example
example = Scope.new("I am an instance variable")
# $global is a global variable so it can be called anywhere
puts $global
# example is a instance of the Scope class. We set the input "I am an instance variable" to the instance variable
# @instance_variable in the initialize method. We then put @instance_variable into a method called instance_message.
puts example.instance_message
# @@clasS_message is a class variable which means it is accessable to the entire class. Notice we also had to
# create a class method with self.class_message as it is not an instance method like instance_message
puts Scope.class_message
# Returns
"I am a global variable"
"I am an instance variable"
"I am a class variable"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment