简体   繁体   English

Ruby Array#to_yaml不会递归调用to_yaml

[英]Ruby Array#to_yaml doesn't call to_yaml recursively

The following code 以下代码

require 'yaml'

class MyObject
  def initialize(value)
    @value = value
  end

  def to_yaml()
    @value + @value
  end
end

puts [MyObject.new("a"), MyObject.new("b")]

Generated the following output on Ruby 2.1.3p242: 在Ruby 2.1.3p242上生成以下输出:

---
- !ruby/object:MyObject
  value: a
- !ruby/object:MyObject
  value: b

Where I expected it to be 我期望在哪里

---
- aa
- bb

As if I called to_yaml on every object inside the Array: 就像我在Array内的每个对象上调用to_yaml

puts [MyObject.new("a").to_yaml, MyObject.new("b").to_yaml]

What am I doing wrong? 我究竟做错了什么?

I'm leaving the previous answer as well, since it might come in handy for someone, but here's the better solution. 我也将保留先前的答案,因为它可能对某人有用,但这是更好的解决方案。

I've actually over-simplified the original problem. 我实际上已经过分简化了原始问题。 I'm trying to get my custom object to be rendered as a YAML sequence [1, 2, 3, ...] . 我试图将我的自定义对象呈现为YAML序列[1, 2, 3, ...] The previous answer could work for objects that are being rendered as Strings. 先前的答案可能适用于呈现为字符串的对象。

Here's the working version: 这是工作版本:

require 'yaml'

class MyObject
  def initialize(value)
    @value = value
  end

  def encode_with coder
    coder.tag = nil
    coder.seq = [@value, @value]
  end
end

puts [MyObject.new("a"), MyObject.new("b")].to_yaml

Some references: 一些参考:

http://blog.mustmodify.com/pages/psych-ruby-1-9-yaml http://blog.mustmodify.com/pages/psych-ruby-1-9-yaml

http://ruby-doc.org/stdlib-1.9.3/libdoc/psych/rdoc/Psych/Coder.html http://ruby-doc.org/stdlib-1.9.3/libdoc/psych/rdoc/Psych/Coder.html

I'm replacing the visit_Array method of the Psych::Visitors::YAMLTree 我要替换Psych::Visitors::YAMLTreevisit_Array方法

class MyVisitor < Psych::Visitors::YAMLTree
  def visit_Array o
    super o.map { |i| i.respond_to?(:to_yaml) ? i.to_yaml : i }
  end
end

Then, I'm dumping the YAML this way: 然后,我以这种方式转储YAML:

a = [MyObject.new("a"), MyObject.new("b")]
visitor = MyVisitor.create
visitor << a
puts visitor.tree.yaml

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM