Reputation: 4524
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
?
Upvotes: 10
Views: 6529
Reputation: 1240
In Ruby 2.1 you can mark single methods as private also like this (space is optional):
class MyClass
private \
def private_method
'private'
end
private\
def private_method2
'private2'
end
def public_method
p private_method
'public'
end
end
t = MyClass.new
puts t.public_method # will work
puts t.private_method # Error: private method `private_method'
# called for #<MyClass:0x2d57228> (NoMethodError)
Upvotes: 2
Reputation: 2115
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
Upvotes: 9
Reputation: 16092
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 :)
Upvotes: 13
Reputation: 9762
It applies to everything under private
i.e greeting
and farewell
To make either of them private you can make greeting
alone private as below:
def greeting
random_response :greeting
end
private :greeting
def farewell
radnom_response :farewell
end
Documentation is available at Module#private
Upvotes: 3