November 2017

Monthly Archives

Let’s talk about self real quick

To understand self, or the concept of self, it will help to understand methods and instances.

A method call in Ruby is the sending of a message to a receiver- the message is the method and the receiver is the object. What is an object? I’m so very glad you asked!

An object in code is a thing with all the data and all the logic required to complete a task. Objects are models and metaphors for the problems we solve in code.

Basically, an object as defined in Ruby is very similar to an object as defined in real life- it’s a thing that has an identity, it can also ‘hold state and manifest behavior by responding to messages’, as this wonderful article on objects from Ruby Monk puts it.

https://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/39-ruby-s-object-model/lessons/127-object-identity-what-is-an-object

An ‘instance’ is an iteration of a Class, so for instance (get it!?!?) – If we have…

class Fresh
def broccoli
puts “Broccoli! Fresh!”
end
end
Fresh.new.broccoli

The instance here would be Fresh.new, with the method broccoli being called on it, returning “Broccoli! Fresh!”

So, now that we know these things, let’s get into self-

“The keyword self in Ruby gives you access to the current object – the object that is receiving the current message.”

So let’s say that self is like the T.A.R.D.I.S. with a fixed chameleon circuit- there is always one and only one T.A.R.D.I.S. but this T.A.R.D.I.S. can be many different things in the context of when it is accessed.

Ok, for those of you who aren’t Dr. Who fans (what are you doing on this blog?) this means that self is a fixed concept, but the identity of self is subject to change. The origin of this changiness (my word, not real) is when and where it is accessed, i.e. within any method you’re using self in. Yea it’s not easy to grasp, just read this blog post a few more times, see if it helps. If it doesn’t, grab yourself a space and time machine and boom, you’ll have all the time in the multiverse to grasp it.