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
  end

  def gold
    @gold
  end

  def take_gold_from(other)
    @gold += other.gold
  end

  private :gold
end

>> m1 = Midas.new(10)
>> m2 = Midas.new(20)
>> 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

Outline

[contents]

Method Scope Slides - Code Like This

/

#