Skip to content

Instantly share code, notes, and snippets.

@cody-code-wy
Created June 1, 2016 16:49
Show Gist options
  • Save cody-code-wy/1492369c630434aff46fa46385d74bc0 to your computer and use it in GitHub Desktop.
Save cody-code-wy/1492369c630434aff46fa46385d74bc0 to your computer and use it in GitHub Desktop.

The self keyword

Self in instance methods

Self referst to the instance of a class it is evoked from. Or in other words, it allows you to address methods on its own instance. This feature is not normally required in ruby. It is most usefull when a method's name is ambiguous between instance methods, and other methods that are in scope.

Defining class methods

Self can also be used to define class methods, for example

class Test

  def instance_method
    puts 'hello from the instance'
  end

  class << self

    def class_method
      puts 'hello from the class'
    end
  end
end

or

class Test

  def instance_method
    puts 'hello from the instance'
  end

  def self.class_methods
    puts 'hello from the class'
  end
end

Both of these examples create identicall results. The methods attached to self (in this context, self is the class, not an instance) are called class methods. You would use these methods like this

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