Reputation: 87
I have a large hash like this:
{"id"=>"1",
"contact_id"=>"15062422",
"status"=>"Complete",
"[question(12), option(24), piped_page(32]" => "Yes",
"[question(13), option(32)]" => "Robert",
"[question(14)]" => "Thing"}
I need to parse the keys that start with '[' to separate the name(value) pairs. The number of names (i.e. question, option, etc) in each key is variable but there are a known number of possibilities.
I'd like to convert each pair into a new has like this:
{:question => 12, :option => 24, :piped_page => 32, :value => "Yes"}
I've thought of using .to_s on each hash element and then doing a variety of string substitutions followed by eval, but the .to_s escapes the double quotes which really complicates things.
Any ideas?
Upvotes: 1
Views: 438
Reputation: 12100
You can use regex to solve it:
str = "[question(12), option(24), piped_page(32)]"
Hash[str.scan /(\w+)\((\w+)\)/]
=> {"question"=>"12", "option"=>"24", "piped_page"=>"32"}
Upvotes: 1