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

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

scoping toggles

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)'

Next: Classes As Objects >> << Previous: Variable Scope



Method Scope Slides - Code Like This