From: Jack Bauer on
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.
--
Posted via http://www.ruby-forum.com/.

From: John Barnette on
On Apr 4, 2010, at 8:18 PM, Jack Bauer wrote:
> 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.
> --
> Posted via http://www.ruby-forum.com/.
>


~ j.