Within a Ruby class definition, what is the scopes of the private keyword in the following scenarios:
class Foo
def bar_public
puts "public"
end
private
def bar_private
puts "private"
end
def bar_public_2
puts "another public"
end
end
Does private only act on bar_private? or on bar_public_2 as well?
A member that is private can be accessed (without any or on any instance of the class) from within code written inside the class definition and all out-of-class definitions for members of the class.
The scope of the private modifier lies with in the class. Members that are declared private cannot be accessed outside the class. Private access modifier is the most restrictive access level. Class and interfaces cannot be private.
A public method can be invoked from anywhere—there are no restrictions on its use. A private method is internal to the implementation of a class, and it can only be called by other instance methods of the class (or, as we'll see later, its subclasses).
PHP - Access Modifierspublic - the property or method can be accessed from everywhere. This is default. protected - the property or method can be accessed within the class and by classes derived from that class. private - the property or method can ONLY be accessed within the class.
In your case both bar_private
and bar_public_2
are private.
That is because both methods are "within scope" of the private
keyword.
> f = Foo.new
#<Foo:0xf1c770>
> Foo.new.bar_private
NoMethodError: private method 'bar_private' called for #<Foo:0xf1c770>
> Foo.new.bar_public_2
NoMethodError: private method 'bar_public_2' called for #<Foo:0xf1c770>
Either way, the best way to answer you question is to open IRB and try it out ;-)
If you find it weird that private
is affecting both bar_private
and bar_public_2
, then rather than use private
, use private :bar_private
after defining bar_private
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With