String to YAML to Hash

J

Jack Bauer

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

John Barnette

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

require "yaml"

hash = YAML.parse the_string
---
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.


~ j.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top