Skip to content

Instantly share code, notes, and snippets.

@rickhull
Created December 10, 2017 01:29
Show Gist options
  • Save rickhull/4e1384c4264a00de57e731dff775e370 to your computer and use it in GitHub Desktop.
Save rickhull/4e1384c4264a00de57e731dff775e370 to your computer and use it in GitHub Desktop.
class Foo
def initialize
@foo = :foo
end
private
def bar
:bar
end
end
f = Foo.new
f.bar #=> NoMethodError private method
class Foo
def public_bar
bar
end
end
f.public_bar #=> :bar
class Foo
def public_bar
self.bar
end
end
f.public_bar #=> NoMethodError private method
# OK, fair enough, private methods cannot be called with receivers (i.e. self.bar)
# But...
class Foo
private
def bar=(val)
@barf = val
end
end
f.bar = 42 #=> NoMethodError private method
# OK, fair enough
# But...
class Foo
def public_bar
self.bar = 99
end
end
f.public_bar #=> 99
f #=> #<Foo:0x0000564c337d45f8 @foo=:foo, @barf=99>
# So, if Foo#bar= is a private method, how come Foo#public_bar can call it on self?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment