Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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