I like the "definition of arbitrary attributes" and I think the OpenStruct in ruby sometimes feels cleaner than using a hash, but I'm curious as to whether there are other specific advantages or use cases that make an OpenStruct a better choice than simply using a Hash.
-
OS is teh slows, but great for prototyping. – Dave Newton Jan 20 '13 at 02:49
2 Answers
OpenStruct
objects are useful when you need something to fit a certain method call interface (i.e. send in a duck-typed object responding to #name
and #value
), or when you want to encapsulate the implementation details, but also want to avoid over-engineering the solution. They also make an awesome stub object, and I often use them in place of framework stubs when I don't need the overhead of a stub/mock.

- 10,632
- 1
- 37
- 47
-
16+1 For mentioning their use in testing. I use them extensively in stubbing HTTP-related bits of data when testing API/web service calls. Quite awesome once you get the hang of it. – Kyle Carlson Aug 31 '13 at 21:55
I think this mostly comes down to a performance decision. From the Ruby Documentation:
An OpenStruct utilizes Ruby’s method lookup structure to and find and define the necessary methods for properties. This is accomplished through the method method_missing and define_method.
This should be a consideration if there is a concern about the performance of the objects that are created, as there is much more overhead in the setting of these properties compared to using a Hash or a Struct.
Additionally, something like a Hash
has additional functionality with all of the methods it provides (has_key?
, include?
, etc.). The OpenStruct
is a very simple object from that standpoint, but if you don't have any concerns from a performance standpoint and just want an easy object to work with, OpenStruct
is a good choice.

- 1
- 1

- 10,323
- 2
- 30
- 45
-
As a further caution, in Ruby 1.9.3 (at least) all the work is done when the OpenStruct is created, rather than on first method use. This makes an OpenStruct expensive, even if you never access any member functions. (Don't know if this has been fixed in a later version). – MZB Apr 21 '16 at 16:08