This site is a preview of the curriculum for our Summer 2018 bootcamp in Burlington, Vermont. As we continue our preparation, courses and lessons will appear and disappear; we will rename, rearrange, clarify, and obfuscate as needed... Please consider this a work in progress and keep checking in.

Ruby Topics:
Method Scope


Method Scope (Public/Protected/Private)

This section covers public/private/protected method scope

Ref.: WGR Ch. 5, The default object (self), scope, and visibility

private methods

  • declared with private keyword
  • only accessible to that specific instance
    • i.e. from inside an instance method of that class
    • i.e. when self is the receiving object

you can't even access your siblings' private parts

class Midas
  def initialize(initial_gold)
    @gold = initial_gold

  def gold

  def take_gold_from(other)
    @gold +=

  private :gold

>> m1 =
>> m2 =
>> m1.take_gold_from(m2)
NoMethodError: private method `gold' called

protected methods

  • available when self is an instance of that class or one of its descendants

    class Midas
      protected :gold
    => 30

scoping toggles

  • private, protected, and public without arguments turn scoping on or off
  • all upcoming methods assume that scope, until another scope is set, or the class definition ends
  • this is the normal way to mark methods' scope

weird top-level scope

(advanced topic)

  1. methods defined outside any class or module become private methods on Object and are available everywhere
  2. private methods defined inside the Kernel are also available everywhere

require, load, raise etc. are Kernel methods

ruby -e 'print Kernel.private_instance_methods(false)'


comments powered by Disqus