Forum: Ruby YAML to anchor same strings in dumps

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
397f61cc4458e13157b4facf72325e5f?d=identicon&s=25 Gennady Bystritsky (Guest)
on 2009-01-30 06:34
(Received via mailing list)
Hi, there

Is there any way to make YAML alias same strings in dumps? The following
code fragment:

require 'yaml'
s = 'a' * 10
puts [ s, s ].to_yaml

Produces this:
---
- aaaaaaaaaa
- aaaaaaaaaa

While I need:
---
- &id001 aaaaaaaaaa
- *id001

Interestingly, if I define s as:
s = [  'a' * 10 ]

The output is aliased just fine:
---
- &id001
  - aaaaaaaaaa
- *id001

Thanks,
Gennady.
397f61cc4458e13157b4facf72325e5f?d=identicon&s=25 Gennady Bystritsky (Guest)
on 2009-01-30 23:49
(Received via mailing list)
>
> ---
> - &id001 aaaaaaaaaa
> - *id001

Found a solution:

module ComplexYamlObject
  def is_complex_yaml?
    true
  end
end

s = 'a' * 10
s.extend ComplexYamlObject
puts [ s, s ].to_yaml

Then the output will be just as I originally wanted:

---
- &id001 aaaaaaaaaa
- *id001

Thought somebody might find it useful,
Gennady.
This topic is locked and can not be replied to.