Last active
December 12, 2019 21:18
-
-
Save savethefails/6716593 to your computer and use it in GitHub Desktop.
I found keeping track of 'self' in Ruby Classes to be exhausting, so I created this handy example illustrating when self changes, where instance variables are stored, and against which self methods are executed.
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
class RubyScope | |
# `self` is the RubyScope Class | |
# (i.e. an Instance of RubyScope MetaClass) | |
@variable_type = 'class instance variable' | |
# Methods are defined in a class, but executd on an instance | |
# Created on self: "RubyScope", Executed on self: "any instance of RubyScope" | |
def initialize | |
# `self` is an Instance of RubyScope Class | |
@variable_type = 'instance variable' | |
end | |
def variable_type | |
# `self` is an Instance of RubyScope Class | |
@variable_type # returns `instance variable` | |
end | |
class << self | |
# `self` is the MetaClass of RubyScope | |
# (i.e. an Instance of a Class' MetaClass.. I think...) | |
@variable_type = 'metaclass instance variable' | |
# Methods are defined in a class, but executd on an instance | |
# Created on self: "RubyScope's MetaClass". Executed on self: "RubyScope Class" | |
def variable_type | |
# `self` is the RubyScope class | |
@variable_type # returns `class instance variable` | |
end | |
# Methods are defined in a class, but executd on an instance | |
# Created on self: "RubyScope's MetaClass's Superclass". Executed on self: "RubyScope's MetaClass" | |
def self.variable_type | |
# `self` is the RubyScope's MetaClass | |
@variable_type # returns 'metaclass instance variable' | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you have an example usage of this?