2017-07-17 102 views
0
irb(main):001:0> a="run: yes" 
=> "run: yes" 
irb(main):002:0> require 'yaml' 
=> true 
irb(main):003:0> YAML.load a 
=> {"run"=>true} 
irb(main):004:0> YAML.load(a, handlers => {'bool#yes' = identity}) 
SyntaxError: (irb):4: syntax error, unexpected '=', expecting => 
YAML.load(a, handlers => {'bool#yes' = identity}) 
            ^
    from /usr/bin/irb:11:in `<main> 

我想yaml val是的,我谷歌找到处理程序将有所帮助。 但似乎我不使用正确的语法。 我尝试搜索相关文档,但失败。如何使用YAML.load与处理程序

回答

0

与上市代码的问题是

  • handlers没有定义任何地方,你可能想:handlers
  • identity没有在任何地方定义,也许想:identity
  • 你缺少你的哈希火箭上的>=>)。

因此,要获得此代码来运行它应该(可能)看起来像

YAML.load("run: yes", :handlers => {'bool#yes' => :identity}) 

然而,就我知道YAML.load第二个参数是一个文件名。

如果你能够改变输入YAML,只是引述值“是”会导致它来通过为一个字符串

YAML.load("a: 'yes'") 
# => {"a"=>"yes"} 

如果您需要在YAML未引用的字符串“是”在解析后被视为'yes',而不是true。我把它拼凑在一起(在this question的帮助下),使用Psych::HandlerPysch::Parser。虽然我不确定是否有另一种更简单/更好的方法来做到这一点,而不必像这样一起破解这一切。

require 'yaml' 

class MyHandler < Psych::Handlers::DocumentStream 
    def scalar(value, anchor, tag, plain, quoted, style) 
    if value == 'yes' 
     super(value, anchor, tag, plain, true, style) 
    else 
     super(value, anchor, tag, plain, quoted, style) 
    end 
    end 
end 

def my_parse(yaml) 
    parser = Psych::Parser.new(MyHandler.new{|node| return node}) 
    parser.parse yaml 

    false 
end 

my_parse("a: yes").to_ruby 
# => {"a"=>"yes"} 
my_parse("a: 'yes'").to_ruby 
# => {"a"=>"yes"} 
my_parse("a: no").to_ruby 
# => {"a"=>false} 

旁注在控制台(and the source):

YAML 
# => Psych 
相关问题