Ruby programming

So, with Learn.co's curriculum, we are taught object oriented Ruby. I'm still trying to understand how everything works...but as I work through each problem it gets a little bit easier.

Hopefully, I get the terminology correct ;-)

So, when building classes that interact with each other, you have to think about what that can mean. It's all about relationships. So if you have a teacher -student relationship, doctor-patient relationship, boss - employee relationship, they all have different ways they relate to each other. 1 boss can have many employees, but typically each employee has only 1 boss (for this example, lets assume that's correct).

When you create an instance of the Boss, you also want to know which employees each boss has. This is different than a basic spreadsheet model, where you would have to write the boss's name each time you enter a new employee.

Then when you create the employee, you link them to the boss.

This can be done by doing this: boss = Boss.new(boss_name)
This creates a new instance of the boss class, saving the boss's name in a name variable @name.
Then you can add the employees via an employee array. In order to get the relationships working properly. So, if you created @employees upon initialization of the Boss class, you can store your instances of your employee class in there, thus creating a connection between the two. This keeps you from having to write out the boss's name each time you enter an employee. It also allows you to change a group of employee's boss by changing the boss name for 1 instance of the boss class instead of every instance of the employees.  It's a great resource for avoiding repetition and having a more functional program.

This would look something like this:

class Boss
    def initialize(name)
         @name = name
         @employees = []
     end
end
This stores the Boss's name and creates an empty array for the employees to be stored.
So, when you create a new instance of the boss class, like this:

justin = Boss.new("Justin")

from within the Employee class, you would do this to add a new employee to the employee class and add their Boss.

jennifer = Employee.new("Jennifer")
jennifer.boss = justin

you would also want to store the Jennifer instance of the employee class in the boss class by doing this.
justin.employee << jennifer

This creates the proper relationships between the boss and the employee that would allow for tracking of say employee attendance, which boss has what employees, and all sorts of information to be tracked and changed in a way that avoids unnecessary repetition and errors.
  


Comments

Popular Posts