Skip to content

Instantly share code, notes, and snippets.

@joshuastr
Created May 3, 2016 04:39
Show Gist options
  • Save joshuastr/bb9d4c305fb8a723d4d50e6abaf7f095 to your computer and use it in GitHub Desktop.
Save joshuastr/bb9d4c305fb8a723d4d50e6abaf7f095 to your computer and use it in GitHub Desktop.
Self
Regarding the self convention, within both a class method, and the class itself, 'self' refers to the given class, however when called
within an instance method, self refers to a specific instance of that class.
class Person
def self.example_class_method
puts "We're calling an example class method"
puts "'self' is always defined. What is 'self' here? Let's see"
p self #Person
puts "That was self!"
end
def example_instance_method
puts "We're calling an example *instance* method"
puts "'self' is defined here, too, but it means something different"
p self #Person Object/instance of the class (#<Person:0x007fa3e30fa990>)
puts "That was self, again, but see how it's an instance of the class"
end
puts "You'll see this as the class is being defined"
puts "in this context self is:"
p self
puts "See? self is the Person class"
end
Person.example_class_method
person = Person.new
person.example_instance_method
# class Post
# attr_writer :title
# def self.author
# "Jimmy"
# end
# def full_title
# "#{@title} by #{class.author}"
# end
# end
# pst = Post.new
# pst.title = "Delicious Ham"
# puts pst.full_title
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment