tags:

views:

1215

answers:

3

In general, what are the advantages and disadvantages of using an OpenStruct as compared to a Struct? What type of general use cases would fit each of these?

+1  A: 

have a look at the API wrt the new method, a lot of the differences can be found there:

Personally, i quite like openstruct as you dont have to define the structure of the object beforehand and just add stuff as you want. I guess that would be its main (dis)advantage?

Omar Qureshi
+7  A: 

With an OpenStruct, you can arbitrarily create attributes. A Struct, on the other hand, must have its attributes defined when you create it. The choice of one over the other should be based primarily on whether you need to be able to add attributes later.

The way to think about them is as the middle ground of the spectrum between Hashes on one side and classes on the other. They imply a more concrete relationship amongst the data than does a Hash, but they don't have the instance methods as would a class. A bunch of options for a function, for example, make sense in a hash; they're only loosely related. A name, email, and phone number needed by a function could be packaged together in a Struct or OpenStruct. If that name, email, and phone number needed methods to provide the name in both "First Last" and "Last, First" formats, then you should create a class to handle it.

Pesto
+3  A: 

I have a few remarks about Struct vs. OpenStruct vs. Hash in my recent blog comment "Structs inside out", just in case someone is interested.

Robert Klemme