Why can't I parse YAML with Ruby?

This is my Ruby code:

require 'yaml' yaml = YAML.parse( ''' foo: "hello, world" ''' ) puts yaml['foo'] 

I get:

 NoMethodError: undefined method `[]' for #<Psych::Nodes::Document:0x007f92a4404d98> 

This is Ruby 2.1.3

+6
source share
2 answers

You should use YAML.load instead of YAML.parse as described in the documentation for analyzing YAML.

 require 'yaml' yaml = YAML.load( ''' foo: "hello, world" ''' ) puts yaml['foo'] # => hello, world 
+4
source

What makes you think that you cannot parse YAML? The error message says that Psych::Nodes::Document does not have a [] method, and this is true, but the fact that you returned a Psych::Nodes::Document object instead of an exception means that the parsing did work.

You can learn more about how Psych YAML AST is developed and how it works in the Psychological Documentation for Psych::Nodes .

+4
source

Source: https://habr.com/ru/post/979958/


All Articles