Ruby/Class/Access level
Материал из Wiki.crossplatform.ru
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
label methods: private or protected will have the indicated visibility until changed or until the definition ends.
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( "Klyde", "Kimball", "Abner", "Teddy Bear" ) name.given # => "Klyde" name.family # => "Kimball" # see what happens when you call nick or pet name.nick name.pet
Ruby gives you three levels of access:
The visibility or access of methods and constants may be set with the methods public, private, or protected. Public methods - Can be called from anywhere in your code. Protected methods - Can be called only inside objects of the class that defines those methods, or objects of classes derived from that class. Private methods - Can only be called inside the current object.
When you use an access modifier, all the methods that follow are defined with that access, until you use a different access modifier.
class Animal def initialize(color) @color = color end public def get_color return @color end private def get_feet return "four" end def get_sound return "Bark" end end