Skip to content

Instantly share code, notes, and snippets.

@ambsvan
Created June 9, 2014 22:37
Show Gist options
  • Save ambsvan/82823cb3eb7060e6075b to your computer and use it in GitHub Desktop.
Save ambsvan/82823cb3eb7060e6075b to your computer and use it in GitHub Desktop.
What is .self?
#What is self?
Self can be confusing because it refers to something different depending on the context.
It refers to the object on which it is called (this could be a class or an instance of a class).
In a class, it refers to the class itself, so if a class is called "Person", self is referring to "Person".
In the context of a class, if you call a def (a new method) inside the class without an explicit receiver, it will create a new instance method.
##In the context of a class, defining a class method on self defines a class method.
Example:
<pre><code>
class Kitten
attr_accessor :cute_name
attr_accessor :color
def initialize(name, color)
@cute_name = name
@color = color
end
def has_pooped?
false
end
def self.has_fur?
true
end
end
</code></pre>
Where "has_fur?"" method changes the class itself so all of the kittens have fur.
"has_pooped?"" method refers to a specific kitten (instance of class Kitten)
DNA is an imprint for a creature and defines what a kitten is.
Kitten DNA is defined in the class, you can have different instances of the kittens.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment