Just started to learn Ruby. I'm confused with Ruby's private
keyword.
Let's say I have code like this
private
def greeting
random_response :greeting
end
def farewell
random_response :farewell
end
Does private
only applied to the #greeting
or both - #greeting
and #farewell
?
A private method is an access modifier used in a class that can only be called from inside the class where it is defined. It means that you cannot access or call the methods defined under private class from outside.
To make a public method private, you prefix its name with a hash # . JavaScript allows you to define private methods for instance methods, static methods, and getter/setters. The following shows the syntax of defining a private instance method: class MyClass { #privateMethod() { //... } }
Private methods are those methods that should neither be accessed outside the class nor by any base class. In Python, there is no existence of Private methods that cannot be accessed except inside a class. However, to define a private method prefix the member name with the double underscore “__”.
It's fairly standard to put private/protected methods at the bottom of the file. Everything after private
will become a private method.
class MyClass
def a_public_method
end
private
def a_private_method
end
def another_private_method
end
protected
def a_protected_method
end
public
def another_public_method
end
end
As you can see in this example, if you really need to you can go back to declaring public methods by using the public
keyword.
It can also be easier to see where the scope changes by indenting your private/public methods another level, to see visually that they are grouped under the private
section etc.
You also have the option to only declare one-off private methods like this:
class MyClass
def a_public_method
end
def a_private_method
end
def another_private_method
end
private :a_private_method, :another_private_method
end
Using the private
module method to declare only single methods as private, but frankly unless you're always doing it right after each method declaration it can be a bit confusing that way to find the private methods. I just prefer to stick them at the bottom :)
In Ruby 2.1 method definitions return their name, so you can call private
on the class passing the function definition. You can also pass the method name to private
. Anything defined after private
without any arguments will be a private method.
This leaves you with three different methods of declaring a private method:
class MyClass
def public_method
end
private def private_method
end
def other_private_method
end
private :other_private_method
private
def third_private_method
end
end
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