如何强制to_yaml以文字块样式输出长字符串?

dan*_*dan 5 ruby yaml

我在散列中有很长的字符串值,希望在YAML中以文字块样式(以>或开头的块|)打印,而不是以行内字符串的形式打印。打电话时有办法强制执行此操作#to_yaml吗?

文字块样式的示例:

---
this: |
  Foo
  Bar
Run Code Online (Sandbox Code Playgroud)

bor*_*gvo 0

这应该可以解决问题:

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
Run Code Online (Sandbox Code Playgroud)

输出:

---
this: |
  Foo
  Bar
Run Code Online (Sandbox Code Playgroud)