Ruby – Reading From Hashes Dynamically

Share

You will probably find various ways to play around with HASH data when you are working with Ruby.

Hash – a dictionary-like collection of unique keys and their values.

However, When it comes to data modeling, there is a typical case, where even though you are dealing with simple HASH objects,  you often need to write some lengthy chunk of code again and again in order to access these data. And who knows what kind of objects and different set of keys and values you will be dealing with.

For example lets take a look at the following object :

Here, We have a simple Car object, with some special attributes (Name, Miles_per_Gallon, Cylinders etc). Dealing with such data won’t cause a headache as it is just one single object. You can simply access these attributes by doing something like this :

We simply created a class with some attribute readers based on those data that we wished to read. Hence, we got our job done.

But Hey ! What if you are dealing with a large  set of objects with probably a different set of keys in each. How are you going to read all of them ? And what about the time that you are going to spend writing your attribute readers for each objects ?

Here is a quick sample :

The Solution

One simple solution is to make use of a common reader class. The only unique thing about this new class will be its special ability to define new methods at runtime.

This code will simply loop through each pairs in your HASH and add the attributes using the define_method function dynamically.

You will now have access to each attribute of the Hash object.

Happy Coding !!

2 Responses

  1. PJ says:

    Sorry, but this is quite inaccurate. These are not JSONs, are Hash objects.

Leave a Reply

Your email address will not be published. Required fields are marked *