user376304
user376304

Reputation: 77

Inserting values into a Hash for YAML dump

I'm creating a hash that will eventually be dumped on disk in YAML, but I need to capture multiple values stored in a file on disk and insert them into a hash. I can successfully create a variable with comma separated values, but I need to insert those values into a my "classes" key:

variable_values = "class1,class2,class3"

Ultimately, I need to get them into my test hash so it simulates something like this:

test_hash = {'Classes' => ['class1', 'class2', 'class3']}

Finally, I can output them to yaml so it looks like this:

--- 
classes: 
- class1
- class2
- class3

What's the best way to iterate through the values and insert them into the hash? Thanks for any help you can offer!

Upvotes: 2

Views: 807

Answers (2)

Andrew Grimm
Andrew Grimm

Reputation: 81691

If you're wanting to serialize Ruby Classes (I'm not able to tell for sure), you'll probably want the following code (courtesy of opensoul.org, and as used in the Small Eigen Collider)

class Module
  yaml_as "tag:ruby.yaml.org,2002:module"

  def Module.yaml_new( klass, tag, val )
    if String === val
      val.split(/::/).inject(Object) {|m, n| m.const_get(n)}
    else
      raise YAML::TypeError, "Invalid Module: " + val.inspect
    end
  end

  def to_yaml( opts = {} )
    YAML::quick_emit( nil, opts ) { |out|
      out.scalar( "tag:ruby.yaml.org,2002:module", self.name, :plain )
    }
  end
end

class Class
  yaml_as "tag:ruby.yaml.org,2002:class"

  def Class.yaml_new( klass, tag, val )
    if String === val
      val.split(/::/).inject(Object) {|m, n| m.const_get(n)}
    else
      raise YAML::TypeError, "Invalid Class: " + val.inspect
    end
  end

  def to_yaml( opts = {} )
    YAML::quick_emit( nil, opts ) { |out|
      out.scalar( "tag:ruby.yaml.org,2002:class", self.name, :plain )
    }
  end
end

The code currently throws an exception if you try to serialize/deserialize anonymous classes (something I could fix but don't need to), and apart from that it works well for me.

Upvotes: 1

J Cooper
J Cooper

Reputation: 17062

You'd probably want something like:

test_hash = {'Classes' => variable_values.split(',')}

Upvotes: 3

Related Questions