Created
June 9, 2014 22:37
-
-
Save ambsvan/82823cb3eb7060e6075b to your computer and use it in GitHub Desktop.
What is .self?
This file contains hidden or 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
| #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