Skip to content

Instantly share code, notes, and snippets.

@notahat
Created May 6, 2010 01:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notahat/391685 to your computer and use it in GitHub Desktop.
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"
@DanielHeath
Copy link

Makes sense to me - isn't that what protected is for?
Is there something else that makes you think it should behave differently?

@gusgollings
Copy link

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

@DanielHeath
Copy link

Ah!

I've become so spoilt by ruby. Nice syntax like this just doesn't get the appreciation it deserves.

@notahat
Copy link
Author

notahat commented May 6, 2010

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.

@DanielHeath
Copy link

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

@notahat
Copy link
Author

notahat commented May 6, 2010

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"

@DanielHeath
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment