Created
August 23, 2023 07:54
-
-
Save danini-the-panini/7d975d051de36a885331967f18f70fa9 to your computer and use it in GitHub Desktop.
Ruby Private and Protected examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo | |
def call_foo | |
foo | |
end | |
def call_self_foo | |
self.foo | |
end | |
def call_other_foo(other) | |
other.foo | |
end | |
private # <-- change this to protected and see what changes | |
def foo | |
puts 'Foo#foo got called' | |
end | |
end | |
class Bar < Foo | |
def bar_call_foo | |
foo | |
end | |
def bar_call_self_foo | |
self.foo | |
end | |
def bar_call_other_foo(other) | |
other.foo | |
end | |
end | |
class NotFoo | |
protected | |
def foo | |
puts 'NotFoo#foo got called' | |
end | |
end | |
Foo.new.call_foo | |
Foo.new.call_self_foo | |
Foo.new.call_other_foo(Foo.new) rescue puts $!.message | |
Foo.new.call_other_foo(Bar.new) rescue puts $!.message | |
Foo.new.call_other_foo(NotFoo.new) rescue puts $!.message | |
Bar.new.call_foo | |
Bar.new.call_self_foo | |
Bar.new.call_other_foo(Foo.new) rescue puts $!.message | |
Bar.new.call_other_foo(Bar.new) rescue puts $!.message | |
Bar.new.call_other_foo(NotFoo.new) rescue puts $!.message | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Foo | |
def call_foo | |
foo | |
end | |
def call_self_foo | |
self.foo | |
end | |
def call_other_foo(other) | |
other.foo | |
end | |
private # <-- change this to protected and see what changes | |
def foo | |
puts 'Foo#foo got called' | |
end | |
end | |
class Bar | |
include Foo | |
def bar_call_foo | |
foo | |
end | |
def bar_call_self_foo | |
self.foo | |
end | |
def bar_call_other_foo(other) | |
other.foo | |
end | |
end | |
class NotFoo | |
protected | |
def foo | |
puts 'NotFoo#foo got called' | |
end | |
end | |
Bar.new.call_foo | |
Bar.new.call_self_foo | |
Bar.new.call_other_foo(Bar.new) rescue puts $!.message | |
Bar.new.call_other_foo(NotFoo.new) rescue puts $!.message | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment