Italo Lemos
Italo Lemos

Reputation: 1022

Object Variables in Ruby

I'm learning Ruby and I found this code example on book, it's about encapsulation. Here it:

class Person
    def initialize(name)
      set_name(name)
    end

   def name
      @first_name + " "+ @last_name
   end

   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

My question is why he doesn't put the attributes first_name and last_name like instance variable at this line first_name, last_name = name.split(/\s+/)? Since in other lines he settled them with @ symbol?

Upvotes: 1

Views: 54

Answers (2)

msergeant
msergeant

Reputation: 4801

It seems to be just a design decision. Perhaps he wants to only set the instance variable in one place.

This could allow him some flexibility later on if more steps need to happen in the setters or if he needs to change the instance variable names or anything really.

Since the book is about encapsulation, he is probably being careful to encapsulate those instance variables as much as possible.

Upvotes: 2

squiguy
squiguy

Reputation: 33380

This is because @ in classes denote instance variables which are exclusive to an instance of the object.

In the set_name method, first_name and last_name are local to the method in which they are created. Thus the author omits the @. He does not want to change the instance variables that are used in the other methods. This is the encapsulation he is talking about. The user cannot directly access these variables but instead has the object change them through the set_first_name and set_last_name methods.

In retrospect, those are poor variable names since there already exists some instance variables with the same name.

Upvotes: 1

Related Questions