Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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