Ruby Encapsulation Tutorial

In this section, we will learn what the Encapsulation is and how it works in Ruby.

What is Encapsulation in Ruby?

Encapsulation in the world of Object Oriented programming languages like Ruby is a concept that refers to the fact that we can hide the state of an object from other objects!

Note: instance variables represent the state of an object

How to Implement Encapsulation in Ruby?

We learned that in Ruby, instance, variables are automatically hidden and cannot be accessed using objects! We are only allowed to use methods if we want to access the value of an instance variable.

This is a great example of encapsulation in Ruby! Basically, by limiting the access to an instance variable only through methods, we control what type of value is assigning to an instance variable, stop the access to an instance variable altogether if necessary and many more type of protection that might become necessary in a program.

This is actually the main reason why the idea of encapsulation came around:

To protect and set controls on how the state of an object is accessed and modified.

Example: implementing encapsulation in Ruby

class Person 

    attr_reader :first_name, :last_name, :id 

    def first_name= (newValue)
        if newValue == "unknown"
            puts "You can't use the value unknown as the value for the first name"
        else 
            @first_name = newValue
        end 
    end 

    def last_name= (newValue)
        if newValue == "unknown"
            puts "You can't use the value unknown as the value for the last name"
        else 
            @last_name = newValue
        end 
    end

    def id= (newValue)
        if newValue == 0
            puts "You can't use the value 0 as the value for the id "
        else 
            @id = newValue
        end 
    end
end 

prs = Person.new 

prs.first_name = "John"
prs.last_name = "unknown"
prs.id = 43

puts prs.first_name, prs.last_name, prs.id 

Output:

You can't use the value unknown as the value for the last name

John

43

In this example, we’ve used setter methods and controlled what type of values can be assigned to the instance variables!

This simple program is an example of encapsulation.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies