这做了我想要的,但通过to_ruby
似乎没有必要:
doc = Psych.parse("foo: 123")
doc.to_ruby.to_yaml
# => "---nfoo: 123n"
当我尝试这样做时,我收到一个错误:
DEV 16:49:08 >> Psych.parse("foo: 123").to_yaml
RuntimeError: expected STREAM-START
from /opt/…/lib/ruby/2.5.0/psych/visitors/emitter.rb:42:in `start_mapping'
我的印象是输入需要是某种流,但我不太明白我需要什么咒语。有什么想法吗?
(顺便说一下,我在这里试图解决的问题是修复一些无法反序列化为 Ruby 的 YAML,因为它引用了不存在的类。YAML 非常复杂,所以我不想只在 YAML 字符串中进行搜索和替换。我的想法是,我可以使用Psych.parse
来获取语法树,修改该树,然后将其转储回 YAML 字符串。
在 https://ruby-doc.org//stdlib-2.3.0_preview1/libdoc/psych/rdoc/Psych/Nodes.html 找到更高级别的文档后弄清楚了咒语,但如果有更好的方法,请告诉我:
doc = Psych.parse("foo: 123")
stream = Psych::Nodes::Stream.new
stream.children << doc
stream.to_yaml
# => "foo: 123n"