String to YAML to Hash

Hi all,

I have a database “text” column with YAML-formatted content.


section:
first_item: this is the first item
second_item: this is the second item

I need to be able to convert all that into a hash. Something tells me
Ruby has something built-in for this sort of task, but I’m not sure.
This is what I tried:

Hash[the_string.split("\n").map{|s| s.split(": ")}]

But that isn’t working. The problem is it essentially ends up formatting
it like:

Hash[["—", “section”, “first_item”, “this is the first item”,
“second_item”, “this is the second item”]]

And that outputs:

{}

If the [[ turned into [ so that it’s not an array within the Hash object
it would work. But whatever, that’s probably not a good solution anyway.
I’m hoping there’s something neater and hopefully already built in to
get me from that first YAML I posted to something more like:

{“section” => {“first_item” => “this is the first item”, “second_item”
=> “this is the second item”}}

Thanks in advance, all.

On Apr 4, 2010, at 8:18 PM, Jack B. wrote:

I have a database “text” column with YAML-formatted content.

require “yaml”

hash = YAML.parse the_string

Hash[the_string.split("\n").map{|s| s.split(": ")}]

Posted via http://www.ruby-forum.com/.

~ j.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs