Skip to content

Instantly share code, notes, and snippets.

@pboling
Last active September 20, 2017 20:41
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 pboling/3e09bb9040e08d29718609ab467ef238 to your computer and use it in GitHub Desktop.
Save pboling/3e09bb9040e08d29718609ab467ef238 to your computer and use it in GitHub Desktop.
class Foo
def calls_bar
bar + " from foo"
end
private
def bar
raise "define #{__method__} in subclasses"
end
end
class SubFooPrivateOverride < Foo
def initialize
puts "the method scope of bar is still private in this subclass: call without self #{bar}"
# The next call will fail
puts "the method scope of bar is still private in this subclass: call with self #{self.bar}"
rescue NoMethodError => e
puts "#{e.class}: #{e.message}"
end
private
def bar
"private subfoo bar"
end
end
class SubFooProtectedOverride < Foo
def initialize
puts "the method scope of bar is changed to protected in this subclass: call without self #{bar}"
puts "the method scope of bar is changed to protected in this subclass: call with self #{self.bar}"
rescue NoMethodError => e
puts "#{e.class}: #{e.message}"
end
protected
def bar
"protected subfoo bar"
end
end
puts SubFooPrivateOverride.new.calls_bar
puts SubFooProtectedOverride.new.calls_bar
@pboling
Copy link
Author

pboling commented Sep 20, 2017

Running this gives:

∴ ruby foo.rb
the method scope of bar is still private in this subclass: call without self private subfoo bar
NoMethodError: private method `bar' called for #<SubFooPrivateOverride:0x007ff725053100>
private subfoo bar from foo
the method scope of bar is changed to protected in this subclass: call without self protected subfoo bar
the method scope of bar is changed to protected in this subclass: call with self protected subfoo bar
protected subfoo bar from foo

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