baudot
baudot

Reputation: 1618

Extended hash wants to load itself from YAML

I'm making a class that's intended to be an intelligent Hash that knows how to load its own values if given a YAML filename and then perform various operations on them. Except that first step is stumping me. Given this code:

    class Agent < Hash
        def initialize
            super
        end

        def load_from_file(filename)
            if (File.file?(filename)) 
                self = YAML.load_file(filename)
            end
        end
    end

...the error message is that one "Can't change the value of self"

How would you make a hash that loads itself from a file?

Upvotes: 0

Views: 39

Answers (1)

Chris Heald
Chris Heald

Reputation: 62668

You're very close. Rather than the self assignment, you just want to use Hash#replace:

class Agent < Hash
    def initialize
      super
    end

    def load_from_file(filename)
      if (File.file?(filename))
        replace YAML.load_file(filename)
      end
    end
end

#replace replaces the keys and values of the calling hash with they keys and values from the passed hash - exactly what you want in this case. However, be sure that you validate that the YAML data is indeed a Hash before calling #replace.

Upvotes: 1

Related Questions