Introduction

Encapsulation controls which parts of the class can be accessed from outside.

Encapsulation keeps a lot of functionality within your classes.

Demo

class Person 
  def initialize(name) 
    set_name(name) # from   w w w.  j  av  a 2s. c  om
  end 

  def name 
    @first_name + ' ' + @last_name 
  end 

  private 

  def set_name(name) 
    first_name, last_name = name.split(/\s+/) 
    set_first_name(first_name) 
    set_last_name(last_name) 
  end 

  def set_first_name(name) 
    @first_name = name 
  end 

  def set_last_name(name) 
    @last_name = name 
  end 
end

Here, the first name and last name are stored separately within each Person object, in object variables called @first_name and @last_name.

The keyword private has been added.

private tells Ruby that any methods declared in this class from there on should be kept private.

Only code within the object's methods can access those private methods, whereas code outside of the class cannot.

Related Topic