Main Content

Clear, concise examples - Ruby classes and objects.

Archive - Originally posted on "The Horse's Mouth" - 2013-02-17 09:52:20 - Graham Ellis

Finding clear, concise examples of how to perform a simple programming task can be surprisingly difficult. "I just want a [Rails] model that doesn't actually use a database table" was an example yesterday. Such shouldn't be difficult, but authors tend to write a simple example and then decide "While I'm at it, I could show X as well" and "I should include Y because it's a good alternative" and "I could be critisized for not covering Z so I'll cover it" ... and the result is an example which doesn't actually fulfill the original requirement of being clear and concise.

I fall into the same trap sometimes ...

On Thursday, I wrote an example to show how a class is defined, how an object is created within that class, and how the object is accessed. Good. And I then extended the example to show:
• how the class can be loaded from a separate file
• how we can use an array of objects
• how we can use a factory method to manufacture objects of a given type
• how we can include class variables and methods as well as object variables
• how we can extend the class to create other similar classes without repeating code

Fortunately, I saved a copy of my original (straightforward) example so that I can re-use it as a first "This is how I create and use an object in Ruby" example - it's [here].

The extended copy (if you would like a comparison, and to move on to all the exciting stuff) is [here], with the class code broken out into a separate file [here].

Examples like this from our ... Ruby Courses.