Ruby 2.0, Yaml using Psych seems to have trouble escaping double quotes. Anyone have an idea on resolving this?
data_ =<<END_
description: "Acme acquires ILM: Lucas says \"Inevitable!\""
END_
ap YAML.load(data_)
produces
/Users/x/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/psych.rb:205:in `parse': (<unknown>): did not find expected key while parsing a block mapping at line 1 column 1 (Psych::SyntaxError)
Escaping the entry with single quotes works, but if it contains single quotes, escaping them results in an error, too.
description: 'Acme acquires ILM: Lucas says "It\'s Inevitable!"'
In an ideal world, the entries would contain proper unicode typographical quotes, but I don't have control over these (although I could replace them before processing with YAML)...
Any ideas on having YAML parse this properly?
Update: answering my question. Found out that it is possible to escape a single quote by duplicating it, so this works:
description: 'Acme acquires ILM: Lucas says "It''s Inevitable!"'
I discovered this by using YAML.dump(the-desired-string)
Your problem is that heredocs act like double quoted strings as far as escaping is concerned. That means that a \"
in your heredoc ends up as just "
in your string. Observe:
>> data_ =<<END_
description: "Acme acquires ILM: Lucas says \"Inevitable!\""
END_
>> puts data_
description: "Acme acquires ILM: Lucas says "Inevitable!""
You want to get a \
into the YAML string so you'll have to escape it:
data_ =<<END_
description: "Acme acquires ILM: Lucas says \\"Inevitable!\\""
END_
Alternatively, use %q{...}
to quote your string so that it behaves more like a single quoted string:
data_ = %q{
description: "Acme acquires ILM: Lucas says \"Inevitable!\""
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With