views:

2024

answers:

1

The following...

require 'yaml'
test = "I'm a b&d string"
File.open('test.yaml', 'w') do |out|
  out.write(test.to_yaml)
end

...outputs ...

--- this is a b&d string

How can I get it to output

--- 'this is a b&d string'

???

+7  A: 

If you want to store an escaped string in YAML, escape it using #inspect before you convert it to YAML:

irb> require 'yaml'
=> true
irb> str = %{This string's a little complicated, but it "does the job" (man, I hate scare quotes)}
=> "This string's a little complicated, but it \"does the job\" (man, I hate scare quotes)"
irb> puts str
This string's a little complicated, but it "does the job" (man, I hate scare quotes)
=> nil
irb> puts str.inspect
"This string's a little complicated, but it \"does the job\" (man, I hate scare quotes)"
=> nil
irb> puts str.to_yaml
--- This string's a little complicated, but it "does the job" (man, I hate scare quotes)
=> nil
irb> puts str.inspect.to_yaml
--- "\"This string's a little complicated, but it \\\"does the job\\\" (man, I hate scare quotes)\""
=> nil

YAML doesn't quote strings unless it has to. It quotes strings if they include things that it would miss if it stored it unquoted - like surrounding quote characters or trailing or leading spaces:

irb> puts (str + " ").to_yaml
--- "This string's a little complicated, but it \"does the job\" (man, I hate scare quotes) "
=> nil
irb> puts %{"#{str}"}.to_yaml
--- "\"This string's a little complicated, but it \"does the job\" (man, I hate scare quotes)\""
=> nil
irb> puts (" " + str).to_yaml
--- " This string's a little complicated, but it \"does the job\" (man, I hate scare quotes)"
=> nil

However, as a YAML consumer, whether the string is quoted shouldn't matter to you. You should never be parsing the YAML text yourself - leave that to the libraries. If you need the string to be quoted in the YAML file, that smells bad to me.

It doesn't matter whether your strings have '&'s in them, YAML will preserve the string:

irb> test = "I'm a b&d string"
=> "I'm a b&d string"
irb> YAML::load(YAML::dump(test))
=> "I'm a b&d string"
irb> YAML::load(YAML::dump(test)) == test
=> true
rampion
Got it. Thanks for the clarification!
neezer
Chuck