|
Red Squirrel Reflections
Dave Hoover explores the psychology of software development
|
Fri, 23 Feb 2007Jamis posted yet another nugget of wisdom. This one was about Ruby's method visibility, which can be tricky for people coming to Ruby from Java or C#. Jamis left one aspect of the protected access level as an exercise for the rest of us, so I figured I'd write up an example that helps illustrate when you would use protected vs. private.
class Sibling
def ask(sib)
sib.tell
end
def spy_on(sib)
sib.secret # will always complain
end
protected
def tell
secret
end
private
def secret
"Charlie tooted"
end
end
rose = Sibling.new
ricky = Sibling.new
begin
puts ricky.tell
rescue
puts "Ricky will only tell another sibling"
end
begin
puts rose.spy_on(ricky)
rescue
puts "Ricky complains when Rose tries to find the secret"
end
puts rose.ask(ricky) # Ricky will tell if Rose asks nicely
One of the main differences for Java developers is that objects of the same class can't see each other's private methods.
|