Ruby Build an Address Book in Ruby Class Design Phone Number Class

Why not put both classes in the same file?

Is it feasible/will it work with both "contact" and "phone number" classes in the same .rb file? Why separate them in the first place? Ultimately, can a ruby programme consist of just one large, well-organised file?

3 Answers

Andrew Stelmach
Andrew Stelmach
12,374 Points

The answer to your question is 'yes, it can'. However, it's considered 'best practice' to separate the classes out into their own files. There are two main reasons for this: one is that classes often (but not always) become quite large, so it's for general readability and organisation of your code.

Secondly, and this is also related to the first reason: a lot of thought and design principles go into organisation of classes in any program - careful thought goes into what classes should be and what those classes should be responsible for. It then feels natural to have files in separate classes.

So, two main, but interrelated reasons for separating them out.

For further reading, google 'SRP' or 'Single Responsibility Principle'.

Rachelle Wood
Rachelle Wood
15,360 Points

This is an important concept too if you ever want to go to another object-oriented language like Java that actually requires you to make a separate file for each class. Great explanation!

Clear and precise answer, thanks very much Andrew.

But if you have a number of related classes, why not place them in a single file (module)? Isn't that better than having to keep track of several .rb files, especially when you want to create an application and deploy it? Thanks