class Psych::Parser

YAML event parser class. This class parses a YAML document and calls events on the handler that is passed to the constructor. The events can be used for things such as constructing a YAML AST or deserializing YAML documents. It can even be fed back to Psych::Emitter to emit the same document that was parsed.

See Psych::Handler for documentation on the events that Psych::Parser emits.

Here is an example that prints out ever scalar found in a YAML document:

# Handler for detecting scalar values
class ScalarHandler < Psych::Handler
  def scalar value, anchor, tag, plain, quoted, style
    puts value

parser =

Here is an example that feeds the parser back in to Psych::Emitter. The YAML document is read from STDIN and written back out to STDERR:

parser =$stderr))

Psych uses Psych::Parser in combination with Psych::TreeBuilder to construct an AST of the parsed YAML document.



Let the parser choose the encoding


UTF-16-BE Encoding with BOM


UTF-16-LE Encoding with BOM


UTF-8 Encoding



Set the encoding for this parser to encoding


The handler on which events will be called

Public Class Methods

new(handler = click to toggle source

Creates a new Psych::Parser instance with handler. YAML events will be called on handler. See Psych::Parser for more details.

# File psych/lib/psych/parser.rb, line 47
def initialize handler =
  @handler = handler
  @external_encoding = ANY

Public Instance Methods

mark # → #<Psych::Parser::Mark> click to toggle source

Returns a Psych::Parser::Mark object that contains line, column, and index information.

static VALUE mark(VALUE self)
    VALUE mark_klass;
    VALUE args[3];
    yaml_parser_t * parser;

    TypedData_Get_Struct(self, yaml_parser_t, &psych_parser_type, parser);
    mark_klass = rb_const_get_at(cPsychParser, rb_intern("Mark"));
    args[0] = SIZET2NUM(parser->mark.index);
    args[1] = SIZET2NUM(parser->mark.line);
    args[2] = SIZET2NUM(parser->mark.column);

    return rb_class_new_instance(3, args, mark_klass);
parse(yaml) click to toggle source

Parse the YAML document contained in yaml. Events will be called on the handler set on the parser instance.

See Psych::Parser and Psych::Parser#handler

# File psych/lib/psych/parser.rb, line 61
def parse yaml, path = yaml.respond_to?(:path) ? yaml.path : "<unknown>"
  _native_parse @handler, yaml, path