Skip to content
Tutorials Center
My learning

Topics

Lesson 81 of 134 ยท Standard Library

Set, OpenStruct and Friends

Learn when to use Ruby's OpenStruct, Set and ObjectSpace::WeakMap, why OpenStruct is a bundled gem you should rarely need, what happened to SortedSet, and the better alternatives.

Ruby's standard library contains a few small container classes that people reach for again and again: Set for unique values, OpenStruct for "an object with whatever attributes I like", and the less famous ObjectSpace::WeakMap for caches that must not keep objects alive. Each one is convenient and each one has a catch. This lesson explains how they work, what the catches are, and what to use instead.

Two pieces of history matter for modern Ruby. Set was a library you had to require for decades; in Ruby 4.0 it is built into the core and Set.new just works (see the full lesson, Sets). OpenStruct went the opposite way: it is now a bundled gem. It still installs with Ruby, and it works in the runner on this page, but in a real project that uses Bundler you must add gem "ostruct" to your Gemfile, and its authors discourage new uses of it. We will see why.

OpenStruct: an object that grows attributes

Ruby Creating and using an OpenStruct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

An OpenStruct stores its attributes in a hash and defines readers and writers for each key, so person.name works like a normal object. You can add fields at any time, read them with [] as well as with a dot, convert to a hash with to_h, and compare two instances by content. This makes it a popular stand-in for parsed JSON ("give me config.database.host instead of config["database"]["host"]") and for quick test data.

The catches

Ruby What OpenStruct quietly allows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The same flexibility that makes OpenStruct pleasant is also what makes it risky:

  • Typos hide. settings.timout returns nil where a normal object or a Struct would raise NoMethodError. The bug travels far from where it started.
  • Name clashes. A field named after a built-in method silently replaces that method on this one object. In the example tricky.class now returns Ruby instead of OpenStruct, and object_id returns 99, which Ruby flags on stderr with warning: redefining 'object_id' may cause serious problems. Code that relies on class or object_id (logging, hashing, debugging tools) breaks in confusing ways.
  • Nesting is manual. A hash inside stays a hash. Tools such as JSON.parse(text, object_class: OpenStruct) convert nested objects, but arrays and shared structure need care.
  • Performance and memory. Each instance builds methods on demand, which is much slower than a Struct or Data, and it gets worse with many instances.

For all of these reasons, the Ruby maintainers moved OpenStruct out of the default libraries. Use it for scripts and prototypes, not for application code.

Better alternatives

You know the fixed set of fields at the time you write the code. Use a Data (immutable) or a Struct (mutable): a typo raises an error and the object is fast. See Struct and Data.

Ruby Data, Struct and Hash instead of OpenStruct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Choose by what you know:

Situation Use
Fixed, known fields; never change Data.define
Fixed fields that change Struct
Keys come from data and vary Hash (with fetch, dig)
Quick script, test double, prototype OpenStruct (add the gem in a real project)

Set: a quick refresher

Set is a collection of unique values with fast membership tests. In Ruby 4.0 you do not need any require; the Sets lesson covers everything in depth, so here we only look at what is most relevant next to the other containers.

Ruby Set essentials

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The last lines show a classic trap. A set (like a hash) finds elements by their hash value, computed when you add them. If you mutate the element afterwards, the stored position no longer matches its hash, and include? gives false even though the element is there. Set#reset rebuilds the index. The lesson: keep elements immutable (strings frozen as needed, Data objects, symbols, numbers).

SortedSet is gone

Older Ruby versions had a SortedSet class that kept elements in order. It was removed from the standard library (it depended on a third-party gem). Referring to it now fails:

Ruby SortedSet no longer exists (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

You get main.rb:1:in '<main>': uninitialized constant SortedSet (NameError), with the source line and a caret under SortedSet (Ruby 4 appends source excerpts to some error messages). The message says nothing about the removal, so remember it. The straightforward replacements: keep a Set and call sort when you need ordered output; keep a sorted Array and insert with bsearch_index (see Sorting and Searching Arrays); or use a gem such as sorted_set when you truly need an always-ordered, mutable set with fast inserts.

ObjectSpace::WeakMap: caches that do not leak

A normal hash keeps its keys and values alive as long as the hash itself lives. A weak map holds its keys without preventing the garbage collector from collecting them. When a key object is collected, its entry disappears. This is the right tool for metadata attached to objects you do not own: a cache of computed data per object, with no manual cleanup.

Ruby WeakMap basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Two properties to remember. First, keys are compared by identity (equal?), so two equal strings are different keys. Second, when an entry disappears depends on the garbage collector and cannot be predicted, so never write code that depends on an entry being gone at a particular moment, and never print cache.size in a test. For a simpler case, where you want a hash that treats keys by identity but keeps everything, use Hash#compare_by_identity (see Hash Patterns). Ruby 3.3 added ObjectSpace::WeakKeyMap, where keys are compared with eql? and hash, which suits caches keyed by strings or other value objects.

ObjectSpace is a low-level window into the garbage collector. Methods such as ObjectSpace.each_object and ObjectSpace.garbage_collect are for debugging tools and special libraries, not for application logic.

Putting it together

A realistic use of these tools: counting unique visitors per page with a Set, and giving the report a lightweight object. The report class uses a Data instead of an OpenStruct so that a typo can never silently return nil.

Ruby Unique visitors per page

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does OpenStruct.new(timeout: 30).timout (a typo) return?

    OpenStruct answers any unknown reader with nil, so typos in field names are silent. A Struct or Data would raise NoMethodError.
  2. 2. In a project that uses Bundler on Ruby 4.0, what do you need to use OpenStruct?

    ostruct is a bundled gem. It comes with Ruby but Bundler only loads gems listed in the Gemfile, so add gem "ostruct".
  3. 3. Which is the best fit when you know the fields in advance and want an immutable value?

    Data.define gives fixed, immutable fields with real methods, argument checking and fast access.
  4. 4. Why does risky.include?([1, 2, 3]) return false after you mutated an array that is in the set?

    Sets find elements by hash. Mutating an element changes its hash but not its stored position. Keep elements immutable, or call reset.
  5. 5. What is true of the keys of an ObjectSpace::WeakMap?

    A WeakMap compares keys with equal? and lets the garbage collector remove entries whose key object is collected.

Summary

  • OpenStruct is a hash with method syntax: flexible, but typos return nil, names can clash, nesting is manual and it is slow. It is a bundled gem; add it to your Gemfile if you must use it.
  • Prefer Data.define, Struct or a plain Hash depending on whether fields are fixed, changing or dynamic.
  • Set is core in Ruby 4.0; keep elements immutable, and use sort instead of the removed SortedSet.
  • ObjectSpace::WeakMap (identity keys) and WeakKeyMap (eql? keys) hold keys weakly for leak-free caches; entry removal timing is up to the garbage collector.

Next: Benchmarking