Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
Using Hash Vs. Object of a Class
3 Posts
Using Hash Vs. Object of a Class

Hi I am a RoR programmer trying to improve my code and its efficiency. Please help me. I have a hash containing 3 elements. 2 of the elements are themselves a hash. Something like this: data_hash = {"a"=>"some big data",

  "b"=>b_hash),
  "c"=>c_hash}

b_hash contains say, 6-8 key-value pairs. c_hash contains say 3-4 key-value pairs.

Currently, I have a class which takes data_hash as parameter. The controller and this class use data_hash. Should I create classes for b_hash,c_hash and store "a" also in a class Or use data_hash for all further processing? Which one is memory-efficient?

Thanks.

Unless these hashes and objects get much MUCH bigger then memory considerations shouldn't be on your mind, when they are you'll need to test the sizes of the objects yourself.

Whether or not to leave things as nested hashes, or create new classes to handle the data is (like your other question) a common computer science question. Having nested hashes is very simple because the structure already exists, but there are three big downsides:

The hash itself doesn't communicate any meaning about the data which will have repurcussions for you and others maintaining your code

Your code, all your code, needs to have a view of all of the data - it's a very "white-box" structure which often means encapsulation is not observed and business logic bleeds out into control classes, etc..

Related to above, you end up with a "dumb bucket" data structure, instead of something with clever methods that encapsulate actions concisely

Mostly by the time you're asking yourself the question of whether or not you should create a class for some data structure - the answer is already: Yes.

Thank you. That helps.

3 Posts
Login to add your message