2017-07-17 29 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 
相關問題