9

以下...

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

...出力 ...

--- this is a b&d string

どうすれば出力できるようになりますか

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

???

4

2 に答える 2

18

エスケープされた文字列を YAML に保存する場合は、YAML に#inspect変換する前に次を使用してエスケープします。

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 は、必要な場合を除き、文字列を引用しません。引用符なしで保存すると見逃されるものが含まれている場合、文字列を引用符で囲みます-引用符文字を囲む、末尾または先頭のスペースなど:

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

ただし、YAML コンシューマとして、文字列が引用符で囲まれているかどうかは重要ではありません。YAML テキストを自分で解析するべきではありません。ライブラリに任せてください。YAML ファイルで文字列を引用する必要がある場合、それは私には悪いにおいがします。

文字列に「&」が含まれているかどうかは関係ありません。YAML は文字列を保持します。

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
于 2009-04-03T21:52:23.057 に答える