Ruby/Class/private
Материал из Wiki.crossplatform.ru
Controlling Access by Making Methods Private
class MyNumber def initialize @secret = rand(20) end def hint puts "The number is #{"not " if secret <= 10}greater than 10." end private def secret @secret end end s = MyNumber.new s.secret s.hint class OurNumber < MyNumber def hint lower = secret-rand(10)-1 upper = secret+rand(10)+1 "The number is somewhere between #{lower} and #{upper}." end end ls = OurNumber.new ls.hint # => "The number is somewhere between -3 and 16." ls.hint # => "The number is somewhere between -1 and 15." ls.hint # => "The number is somewhere between -2 and 16."
When you make a method private, it"s not accessible outside the object it"s defined in
class Animal def initialize(color) @color = color end private def get_color return @color end end class Dog < Animal def initialize(color) @animal = Animal.new(color) end def get_info return @animal.get_color end end dog = Dog.new("brown") puts "The new animal is " + dog.get_info animal2 = Animal.new("red") puts "The new animal is " + animal2.get_color