Last active
April 9, 2016 01:05
-
-
Save kiefer136/6c79d67369c1f63e91b3a02aff5ca58b to your computer and use it in GitHub Desktop.
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
--- question: how self refers to different objects depending on where it is in a Ruby program --- | |
Self refers to different objects by allowing you to access the class self is called upon. If you were to have a self.method inside a class named 'Person' instead of having to write Person.method, you can use self to call Person. Self calls its parent class if its inside a method and prints the methods class name. If self is called outside of a method in the same class, it will print the class, although it will give it an object value aswell. |
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 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 | |
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 somthing different" | |
p self | |
puts "that was self, again, but see how its'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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment