gpt4 book ai didi

ruby - 在 Ruby 中,有没有办法在某些值为 nil 时使用 XmlSimple?

转载 作者:数据小太阳 更新时间:2023-10-29 08:41:12 25 4
gpt4 key购买 nike

因为 nil 会阻塞 XmlSimple:

>> require 'xmlsimple'
=> true

>> XmlSimple.xml_out([{'a' => 1}, {'a' => 3}])
=> "<opt>\n <anon a=\"1\" />\n <anon a=\"3\" />\n</opt>\n"

但是如果是下面的,那么就会报错:

>> XmlSimple.xml_out([{'a' => 1}, {'a' => nil}])
ArgumentError: Use of uninitialized value!
from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:798:in `value_to_xml'
from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:794:in `each'
from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:794:in `value_to_xml'
from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:848:in `value_to_xml'
from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:842:in `each'
from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:842:in `value_to_xml'
from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:807:in `value_to_xml'
from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:794:in `each'
from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:794:in `value_to_xml'
from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:239:in `xml_out'
from /Library/Ruby/Gems/1.8/gems/xml-simple-1.0.12/lib/xmlsimple.rb:259:in `xml_out'
from (irb):4

最佳答案

如果你看一下 documentation它提到在使用 xml_out 时你应该避免使用 nil 值。我会推荐以下方法之一:

# To create an empty anon element:
XmlSimple.xml_out([{'a' => 1}, {}])
=> "<opt>\n <anon a=\"1\" />\n <anon></anon>\n</opt>\n"

# To create an anon element with a blank 'a' attribute:
XmlSimple.xml_out([{'a' => 1}, {'a' => ''}])
=> "<opt>\n <anon a=\"1\" />\n <anon a=\"\" />\n</opt>\n"

# To remove the attribute entirely (with value of 3),
# but still create an empty anon tag:
XmlSimple.xml_out([{'a' => 1}, {'-a' => 3}])
=> "<opt>\n <anon a=\"1\" />\n <anon />\n</opt>\n"

# To remove the attribute entirely (with value of nil),
# but still create an empty anon tag:
XmlSimple.xml_out([{'a' => 1}, {'-a' => nil}])
=> "<opt>\n <anon a=\"1\" />\n <anon />\n</opt>\n"

关于ruby - 在 Ruby 中,有没有办法在某些值为 nil 时使用 XmlSimple?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5123576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com