RubyGuides
Share this post!

Using Struct and OpenStruct

Sometimes you just want an object that can store some data for you, the struct class is very useful in that situation.

openstruct

Getting Started

To create our Struct we pass in a series of symbols, which will become the instance variables of this class. They will have accessors defined by default (both for reading and writing).

Now you can create new objects of this class with new:

Structs can be tricky

There are some differences with a “normal” class that you need to be aware of. For example, you may have noticed that the class of our john object is just “Class”. To change this, we can do one of the following:

Both of these options will cause our new objects to have the class name we want. Another caveat with Struct-generated classes is that they won’t enforce the correct number of arguments for the constructor. For example, with a proper class you would see this error:

But if you are using Struct the missing arguments will be nil, so keep this in mind when working with Struct.

Using OpenStruct

If you just need a one-off object, then you should consider using OpenStruct instead.

Warning: OpenStruct is slow and you shouldn’t use it on production apps, according to schneems on this reddit comment. Also I found this blog post that has some benchmarks supporting this.

The main difference with Struct is that it just produces objects, in other words, you can’t call cat.new in the example above to get more objects like it.

Conclusion

As long as you are aware of the special characteristics of each of these clases you will be fine. Now go and start coding!