A class with public, protected and private accessors : Access level « Class « Ruby






A class with public, protected and private accessors



#!/usr/bin/env ruby

class Names
  def initialize( given, family, nick, pet )
    @given = given
    @family = family
    @nick = nick
    @pet = pet
  end

# these methods are public by default

  def given
    @given
  end

  def family
    @family
  end

# all following methods private, until changed

  private

  def nick
    @nick
  end

# all following methods protected, until changed

  protected

  def pet
    @pet
  end

end

name = Names.new( "K", "A", "B", "T" )

puts name.given 
puts name.family

 








Related examples in the same category

1.Ruby gives you three levels of access:
2.When you use an access modifier, all the methods that follow are defined with that access, until you use a different access modifier.
3.label methods: private or protected will have the indicated visibility until changed or until the definition ends.