Why is Ruby so full of class?

Because it is object oriented!

30/11/2014

This week I'm going to cover Ruby Classes! The best definition of classes I could find is that they are object blueprints. You put the object's attributes and methods inside the class, then you create a new object of that class by instantiating it. That may sound confusing but I am sure you will understand it after looking at an example.

class Person attr_accessor :name, :age, :gender, :profession def initialize @name = "Lucas" @age = 20 @gender = "Male" @profession = "Systems Analyst" end def print_info p "Name: #{@name}" p "Age: #{@age}" p "Gender: #{@gender}" p "Profession: #{@profession}" end end person = Person.new person.print_info

On the example above, we create a blueprint for a person with name, age, gender and profession. We created the getters and setters using attr_accessor and initialized all the attributes. Then we created a method to print all the info. Finally we created an object of the class Person using Person.new and called its method print_info.

The output is: Name: Lucas Age: 20 Gender: Male Profession: Systems Analyst

That's it for today, later on I'll post a more in-depth tutorial on Ruby Classes.