O'Reilly logo

The Book of Ruby by Huw Collingbourne

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required