一些 yaml 对象确实引用了其他对象:
irb> require 'yaml'
#=> true
irb> str = "hello"
#=> "hello"
irb> hash = { :a => str, :b => str }
#=> {:a=>"hello", :b=>"hello"}
irb> puts YAML.dump(hash)
---
:a: hello
:b: hello
#=> nil
irb> puts YAML.dump([str,str])
---
- hello
- hello
#=> nil
irb> puts YAML.dump([hash,hash])
---
- &id001
:a: hello
:b: hello
- *id001
#=> nil
请注意,它并不总是重用对象(字符串只是重复),但有时会(散列定义一次并通过引用重用)。
YAML 不支持字符串插值——这似乎是你想要做的——但你没有理由不能更详细地对其进行编码:
intro: Hello, dear user
registration:
- "%s Thanks for registering!"
- intro
new_message:
- "%s You have a new message!"
- intro
然后您可以在加载 YAML 后对其进行插值:
strings = YAML::load(yaml_str)
interpolated = {}
strings.each do |key,val|
if val.kind_of? Array
fmt, *args = *val
val = fmt % args.map { |arg| strings[arg] }
end
interpolated[key] = val
end
这将为interpolated 产生以下结果:
{
"intro"=>"Hello, dear user",
"registration"=>"Hello, dear user Thanks for registering!",
"new_message"=>"Hello, dear user You have a new message!"
}