The simplest way to define levels of privacy for a method is to put the public, protected, or private keyword before it, as such:
private
def private_method
puts 'a public method called this private method'
end
Note that you do NOT need to specify an end statement to correspond to the private statement: any method defined after the private statement will be private unless otherwise specified with another permissions modifier statement.
You can also pass symbol arguments to the private, public and protected functions to make the corresponding methods private, public or protected. For example,
def private_method
puts 'a public method called this private method'
end
private :private_method
would produce the same result as the previous example. For me, it's much easier to call the private function with a symbol after the function definition. That was a function definition is sort of in two parts: the actual logic and the permission setting. Here's a test file that demonstrates private, protected, and public methods:
class PrivateTest
def initialize
@size = 5
end
def this_is_private x
'this should be private '+x
end
private :this_is_private
def this_is_public x
this_is_private x
end
def private_again
puts 'hello, a private method was called'
end
private :private_again
def protected_method
puts 'mustve been called from a class or subclass'
end
protected :protected_method
def call_protected
protected_method
end
def is_it_public?
puts 'yep its public'
end
end
class ProtectedTest < PrivateTest
end
puts 'commencing tests'
pvt = PrivateTest.new
ptc = ProtectedTest.new
# pvt.this_is_private
pvt.this_is_public 'hello' #works
# pvt.private_again
# pvt.protected_method
pvt.call_protected
pvt.is_it_public?
# ptc.this_is_private
ptc.this_is_public 'hello'
# ptc.private_again
# ptc.protected_method
ptc.call_protected
ptc.is_it_public?
puts 'all passed.'
The commented out tests cause an error, but the uncommented tests run without error. As far as I can tell, there is no way to have protected static variables.
So that's how public and private work in ruby.
No comments:
Post a Comment