Skip to content

Instantly share code, notes, and snippets.

@savethefails
Last active December 12, 2019 21:18
Show Gist options
  • Save savethefails/6716593 to your computer and use it in GitHub Desktop.
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.
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
@christhekeele
Copy link

Do you have an example usage of this?

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