-
-
Save notahat/391685 to your computer and use it in GitHub Desktop.
class A | |
def hello | |
"A#hello" | |
end | |
def method_missing(method, *args) | |
"A#method_missing" | |
end | |
protected :hello | |
end | |
p A.new.hello # => "A#method_missing" |
Dear Dan,
I believe what is being explored here is not the general nature of protected, but the syntax whereby you can simply reference a method name to be protected. (Ordinarily, usage examples involving protected show protected methods being defined below the protected keyword).
Regards,
Gus
Ah!
I've become so spoilt by ruby. Nice syntax like this just doesn't get the appreciation it deserves.
Ok, clearly I didn't get the point across. Let me give another example:
class A
def hello
"A#hello"
end
end
class B < A
def hello
"B#hello"
end
protected :hello
end
p A.new.hello # => "A#hello"
I expected that, if I declare a method as protected, I would always get an exception when I try to call the method from outside the class. Instead, I get the superclass method if one is defined.
It's not protected in class A.
p B.new.hello gives me a
NoMethodError: protected method `hello' called for #<B:0x1014b2d08>
from (irb):16
Crap, stuffed that up. Ok, try this on for size:
class A
def hello
"A#hello"
end
def method_missing(method, *args)
"A#method_missing"
end
end
class B < A
def hello
"B#hello"
end
def goodbye
"B#goodbye"
end
protected :hello, :goodbye
end
p B.new.hello # => "A#method_missing"
p B.new.goodbye # => "A#method_missing"
And also
A.new.hello
=> "A#hello"
Right, so you can hide functionality in a subclass that is provided by the superclass.
That sounds like a bad idea, since it sort of stops you being able to rely on object-oriented polymorphism.
Makes sense to me - isn't that what protected is for?
Is there something else that makes you think it should behave differently?