Friday, July 21, 2006

Ruby for newbies (Part 1) : Encapsulation made easy

You have to keep one important thing in mind before you develop a new class: it’s called Encapsulation.
Why? Well, it’s basically because in order to maintain your object consistency isn’t a good idea to allow the world to access your object instance variables directly. So if you know other programming languages, lets said Java for example, you would have to create your own methods for every attribute you create, getters and setters they said... (Yes you can do it automatically with eclipse or whatever)
Welcome to Ruby, a wonderful world that will let you focus in the solution domain instead on the complicated keywords. So, in this example I will show an Example class and we will ask it to speak one word.

class Person
attr_reader :name

As you can see, we first create this shortcut that will act as our accessor method (getter) to the real instance variable called name (you could add as many as you need!)

def initialize(therealname)
@name=therealname
end
end

Then, we just create the initialize method to setup the real name of our variable, and note the “@” at the beginning, yes that means this is our own instance variable.

puts Person.new("Vic").name

So, we execute our small class , and as we can see, because of the “puts” sentence : ) , we create a new Person, and we call it “Vic”, then we ask to our class (yes, public by default) method, to give us his name,“Vic”. Does anybody know an easy way to do it?


3 comments:

Anonymous said...

Hoow, great language, and great built-in features.. no more Java!

Anonymous said...

Hmm I love the idea behind this website, very unique.
»

Anonymous said...

I really enjoyed looking at your site, I found it very helpful indeed, keep up the good work.
»