Quickie Objects in Ruby

Sometimes you need a quick object one-off object. Maybe you’re writing a Fake Object that needs to mimic a subset of a real library’s functionality. Ruby provides several facilities which make it easy to throw together objects without the ceremony of writing a dedicated class.


If all you need is an object which responds to certain accessor calls with known values, OpenStruct may be the way to go:

Just be aware that OpenStruct objects are so forgiving they may not flag a typo the way you might expect:


If all you need is an object with a few custom methods, you can use plain old Object. You can then adorn the blank object with singleton methods until it has the desired behavior:

If you are using ActiveSupport, you may find it convenient to use #returning to build your quickie objects:

Singleton Classes

If you want to do more extensive customization of your one-shot object, an alternative to singleton method definition is to use a singleton class definition:

Here we’re customizing the singleton class (or “eigenclass”) associated with an individual object.

All together now

Here’s some code I wrote yesterday which uses all three of these techniques to fake out a small subset of the FlickrFu library API:

Note how in this example I’m tacking extra methods onto Hashes as well as plain Objects.


While not quite as easy as building literal arrays and hashes, Ruby lets you create quick single-use objects with little hassle. If you are only going to use an object in one place, consider eschewing a class definition and just instantiating a singleton.