MySelf.to_s

Struct vs. OpenStruct vs. Hash

All three classes offer functionality with some similarities and overlap. Sometimes you can use them interchangeably. Still there are some guidelines you can use to decide when to use which of these. As always — take these recommendations with a grain of salt. If you have your own different rules of thumb let us know.

Use Struct if

  • you need a data container and fields are fixed and known beforehand (i.e. at time of writing of the code),
  • you need a structured Hash key,
  • you want to quickly define a class with a few fields,
  • you need to detect errors caused by misspelled field names.

Use OpenStruct if

  • the number of fields is fixed at runtime but varies frequently during development time (this is often the case for objects that should hold the result of command line option parsing),
  • you need a mock or a want to quickly have objects at hand which can be filled via usual attribute setters and getters. You might want to replaced with a proper class (or Struct) later — with explicit attribute declarations via attr_accessor and relatives.

Use Hash if

  • the number of fields is unknown at coding time,
  • there is a potentially unlimited number of fields (e.g. when reading key values from a file as is often the case for script based text processing).

Now it also becomes apparent why I indicated that Symbols are appropriate for naming Struct fields: when defining a Struct you are actually declaring attributes much the same way as with an ordinary class. Still, Struct is a bit inconsistent here when it allows Symbols and Strings as keys for the Hash like access via [] and []=. The convenience of being able to use both probably outweighs this inconsistency. Overall that Hash likelyness is probably one of the less important features of Struct. You are likely going to use it when refactoring from / to real Hashes of if you have an application that has to deal with several Structs in a uniform way and needs to use metadata (obtained via #members) to access fields.

(Source: blog.rubybestpractices.com)

  1. memiux posted this