Access controls refers to the methods which allow you to set the access to classes, methods and other members. They are used to encapsulate the components so that we can maintain security of these methods throughout the project.
Ruby gives us three types of access controls namely :
- Public
- Protected
- Private
Public
- A public method can be called by everyone in which no access control is required. This purely means that every instance of the class can call them. All methods are public by default except initialize which is private by default.
class Cars
def car_name
"Audi A9"
end
private
def car_type
"SUV"
end
protected
def car_chasis_number
"ABCDE12345"
end
end
c = Car.new
c.car_name #This will be called successfully.
c.car_type #This Will give an access violation error
c.car_chasis_number #This will give an access violation error
Private
class A
def main_function
function1
end
private
def function1
puts "hello from #{self.class}"
end
end
class B < A
def main_function
function1
end
end
A.new.main_function #This will be called successfully and the output will be hello from A
B.new.main_function #This will be called successfully and the output will be hello from B
Protected
class A
def main_function
function1
end
protected
def function1
puts "hello from #{self.class}"
end
end
class B < A
def main_function
function1
end
end
class C < A
def main_function
self.function1
end
end
A.new.main_function #This will be called successfully and the output will give Hello from A
B.new.main_function #This will be called successfully and the output will give Hello from B
C.new.main_function #This will be called successfully and the output will give Hello from C
0 Comment(s)