Skip to content

Instantly share code, notes, and snippets.

@gbrl
Last active May 3, 2016 16:46
Show Gist options
  • Save gbrl/6e5f587c855f31302523334b2a6f6a28 to your computer and use it in GitHub Desktop.
Save gbrl/6e5f587c855f31302523334b2a6f6a28 to your computer and use it in GitHub Desktop.

"Ruby's self keyword"

Inside a class definition, if you define a method starting with "self." you're creating a method that can be called on the class itself, not on an instance of that class. Example:

class Contact
  def self.all
    # returns an array of all contacts
  end
end

This allows you to call

Contact.all

which could potentially return an array of all contacts.

Another way of doing this, inside your class defintino is by using "class << self". This is a shortcut that saves you having to write "self." at the beginning of each class method name. Example:

class Contact
  class << self
  def all
    # returns an array of all contacts
  end
end

Just like the code on lines 5-9, allows you to call Contact.all, which could potentially return an array of all contacts.

However, if you have an instance of a Person

contact = Contact.new

you can't call

contact.all

because the "all" method belongs to the class, not instances of the class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment