Saving Singletons
Let’s take a look at a concrete example of a problem mentioned earlier, namely, the inability to use marshaling to save and load a singleton. In singleton_m.rb I have created an instance of Object, ob
, and then extended it in the form of a singleton class that is given the additional method, xxx
:
singleton_m.rb
ob = Object.new class << ob def xxx( aStr ) @x = aStr end end
The problem arises when I try to save this data to disk using Marshal.dump
. Ruby displays an error message: “singleton can’t be dumped (TypeError).”
YAML and Singletons
Before considering how you might deal with this, let’s briefly take a look at how YAML would cope in this situation. The program singleton_y.rb tries to save the singleton that I created a moment ...
Get The Book of Ruby now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.