RubyTalks[1]

Damir Svrtan

Method visibility in Ruby

Ruby != Java

grep protected * -lR | wc -l

cd Rails

185

Differences between Ruby & Java

Public methods

can be accessed from anywhere.

Ruby & Java:

subclasses inherit public methods.


  class Person

    def age
      rand(1..100)
    end

  end


  Person.new.age

  => 83

Protected methods

Ruby & Java:

subclasses inherit protected methods.

methods can't be accessed outside the class definition.

Ruby:


  class Person

    protected

    def age
      @age
    end

  end


  Person.new.age


  => protected method `age' called for #<Person:0x007fd901098fd0>

Java:

methods can't be accessed outside the class definition or outside of the same package.

Ruby & Java:

methods can be called inside of the class definition on objects of the same class.

Private methods

methods can't be accessed outside the class definition.

Ruby & Java:

Ruby:

subclasses inherit private methods.

Java:

subclasses don't inherit private methods.

Ruby:

can't be called with an explicit receiver


  class Person

    def initialize(age=25)
      @age = age
    end

    def whats_my_age_again?
      self.age
    end

    private

    def age
      @age
    end

  end


  puts Person.new.whats_my_age_again?

  private method `age' called for #<Person:0x007fc06d0d4b18 @age=25>

Fix


  class Person

    def initialize(age=25)
      @age = age
    end

    def whats_my_age_again?
      age
    end

    private

    def age
      @age
    end

  end


  puts Person.new.whats_my_age_again?

  25

Java:

can be called with an explicit receiver

can be called on objects of the same

class in the class definition

Where the hell do I use protected methods?


  class City

     attr_accessor :name, :county, :mayor

     def initialize(name, county, mayor)
        @name = name
        @county = county
        @mayor = mayor
     end

     def ==(other)
       other.class == City && self.full_location == other.full_location
     end

     protected

       def full_location
         "#{name.titleize} #{county.titleize}"
       end
  end

  moj_voljeni_grad = City.new('Zagreb', 'Grad Zagreb', 'Milan Bandic')

  moj_omrazeni_grad = City.new('Zagreb', 'Grad zagreb', 'scumbag')

Two ways to define protected and private methods in Ruby


  class Person

    protected

    def has_sti?
      @has_sti
    end

    private

    def age
      @age
    end

  end

  class Person

    protected def has_sti?
      @has_sti
    end

    private def age
      @age
    end

  end

Since Ruby 2.0:

Exception to the no-explicit-receiver rule for private methods are setters


  class Person

    private
    
    def age=(value)
      @age = value
    end

    def age
      @age
    end
  end


  person = Person.new

  person.age

  => private method `age' called for

  person.age = 25

THNX

RubyTalks[1]

By Damir Svrtan

RubyTalks[1]

  • 1,214