to_yaml にリテラル ブロック スタイルで長い文字列を出力させるにはどうすればよいですか?
概要
ハッシュ内に長い文字列値があり、それをインライン文字列としてではなく、YAML のリテラル ブロック スタイル (> または | で始まるブロック) で出力したいと考えています。 #to_yaml を呼び出すときにこれを強制する方法はありますか?
リテラルブロックスタイルの例:
---
this: |
Foo
Bar
解決策
これでうまくいくはずです:
require 'yaml'
require 'psych'
long_string = "Foo\nBar"
yaml_output = Psych.dump({ "this" => long_string }, { style: :literal })
# Replacing `|-` with `|`
yaml_output.gsub!("|-", "|")
puts yaml_output
出力:
---
this: |
Foo
Bar