Created
March 27, 2015 15:19
-
-
Save sk187/a2d1e525243b57aa45f3 to your computer and use it in GitHub Desktop.
Ruby Variable Scope
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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