YAML

suggest change

YAML is a text format for structured data. It is a superset of JSON, adds comments, anchors and multi-line strings, and uses indentation instead of braces. Ruby ships with Psych, a binding to the C library libyaml. require 'yaml' loads it and sets the YAML constant to Psych, so YAML.load and Psych.load are the same method.

Loading application settings from a YAML file (per-environment sections, ERB, layering with environment variables) is covered in Configuration files. This article goes deeper into YAML itself: the loading API and its safety options, more typing traps, multi-document streams, emitting, custom types and tags, the node tree, and the event-based streaming parser. For the security background see Application security, and for JSON see JSON with Ruby.

The examples were run with Ruby 4.0 and psych 5.3 (libyaml 0.2.5).

What YAML turns into

Psych maps YAML nodes to core Ruby objects. Flow style ([a, b], {k: v}) and block style (indented lines) produce the same result:

require 'yaml'

doc = <<~YAML
  name: Bookshelf
  version: "2.1"
  tags: [ruby, books]          # flow sequence
  limits: {daily: 100, burst: 10}
  price: 12.50
  big: 1_000_000
  hex: 0xff
  released: 2026-10-17
  started_at: 2026-10-17 09:30:00 +02:00
  enabled: true
  nothing: null
  ratio: .inf
YAML

data = YAML.safe_load(doc, permitted_classes: [Date, Time])
data.each { |k, v| puts "#{k.ljust(11)} #{v.class.to_s.ljust(10)} #{v.inspect}" }
name        String     "Bookshelf"
version     String     "2.1"
tags        Array      ["ruby", "books"]
limits      Hash       {"daily" => 100, "burst" => 10}
price       Float      12.5
big         Integer    1000000
hex         Integer    255
released    Date       #<Date: 2026-10-17 ((2461331j,0s,0n),+0s,-Infj)>
started_at  Time       2026-10-17 09:30:00 +0200
enabled     TrueClass  true
nothing     NilClass   nil
ratio       Float      Infinity

Date and Time are not basic types, so they have to be listed in permitted_classes:. Without that, the same call raises Psych::DisallowedClass.

Loading: load, safe_load and their options

Since psych 4, YAML.load is YAML.safe_load with the same defaults, and YAML.unsafe_load is the old behaviour that can instantiate any class. The keyword options are the same for load, safe_load, load_file and safe_load_file:

Option Default Effect
permitted_classes: [] extra classes allowed besides String, Integer, Float, nil, true, false, Array, Hash
permitted_symbols: [] if non-empty, only these Symbols may appear (requires Symbol in permitted_classes)
aliases: false allow &anchor / *alias
symbolize_names: false Hash keys become Symbols
freeze: false deep-freeze the result
filename: nil name used in error messages
fallback: nil value returned for an empty document
strict_integer: false don't read 1,000 as an Integer
require 'yaml'

doc = "mode: :fast\nlevel: :debug\n"

p YAML.safe_load(doc, permitted_classes: [Symbol])
p YAML.safe_load(doc, permitted_classes: [Symbol], permitted_symbols: %i[fast debug])
begin
  YAML.safe_load(doc, permitted_classes: [Symbol], permitted_symbols: %i[fast])
rescue Psych::DisallowedClass => e
  puts "#{e.class}: #{e.message}"
end

cfg = YAML.safe_load("db:\n  hosts: [a, b]\n", symbolize_names: true, freeze: true)
p cfg
p [cfg.frozen?, cfg[:db].frozen?, cfg[:db][:hosts].frozen?, cfg[:db][:hosts][0].frozen?]

p YAML.safe_load("")
p YAML.safe_load("", fallback: {})
p YAML.safe_load("# only a comment\n", fallback: {})
p YAML.load_file("empty.yml")
p YAML.load_file("empty.yml", fallback: {})
{"mode" => :fast, "level" => :debug}
{"mode" => :fast, "level" => :debug}
Psych::DisallowedClass: Tried to load unspecified class: Symbol
{db: {hosts: ["a", "b"]}}
[true, true, true, true]
nil
{}
{}
nil
{}

An empty file or one that has only comments loads as nil, which breaks code like config['port']. Pass fallback: {} (or write YAML.load_file(path) || {}) when the file may be empty.

permitted_symbols: is useful when a file may contain Symbols but you know which ones are valid: anything else is rejected while loading, and the list documents the values you expect.

Errors

All Psych exceptions inherit from Psych::Exception, a RuntimeError. Syntax errors carry the file name, line and column:

require 'yaml'

begin
  YAML.load_file('broken.yml')
rescue Psych::SyntaxError => e
  puts e.message
  p [e.file, e.line, e.column, e.problem, e.context]
end

begin
  YAML.safe_load("key: [1, 2\n", filename: 'inline.yml')
rescue Psych::SyntaxError => e
  puts e.message
end

p Psych::SyntaxError.ancestors.take(3)
(broken.yml): mapping values are not allowed in this context at line 3 column 8
["broken.yml", 3, 8, "mapping values are not allowed in this context", nil]
(inline.yml): did not find expected ',' or ']' while parsing a flow sequence at line 1 column 6
[Psych::SyntaxError, Psych::Exception, RuntimeError]

broken.yml has port: indented by three spaces instead of two under server:. When you load YAML from a String, pass filename: so the message says where the text came from instead of (<unknown>).

More typing traps

Configuration files shows the best-known surprises: 1.10 becomes 1.1, 01234 is octal, and NO is false. Psych implements YAML 1.1, which has a few more:

require 'yaml'

p YAML.load("on:\n  push:\n    branches: [main]\n")
p YAML.load("a: 1,000\nb: 12:30\nc: 0o17\n")
p YAML.load("a: 1,000\nb: 12:30\n", strict_integer: true)
p YAML.load("on: off\nYes: No\n")
{true => {"push" => {"branches" => ["main"]}}}
{"a" => 1000, "b" => 45000, "c" => "0o17"}
{"a" => "1,000", "b" => 45000}
{true => false}

Strings: quoting and block scalars

YAML has three quoting styles and two block styles for multi-line text. Single quotes are literal (a quote is escaped by doubling it); double quotes support backslash escapes. A | block keeps newlines; a > block folds lines into spaces and turns blank lines into newlines. A - after the indicator strips the final newline, a + keeps all trailing blank lines:

require 'yaml'

doc = <<~'YAML'
  literal: |
    line one
      indented line
    line three
  folded: >
    This long paragraph
    is folded into
    a single line.

    A blank line starts a new one.
  strip: |-
    no trailing newline
  keep: |+
    keeps trailing blank lines

  single: 'It''s single-quoted, \n stays as is'
  double: "Tab:\tNewline:\nEnd"
  empty_str: ""
YAML

YAML.safe_load(doc).each { |k, v| puts "#{k.ljust(9)} #{v.inspect}" }
literal   "line one\n  indented line\nline three\n"
folded    "This long paragraph is folded into a single line.\nA blank line starts a new one.\n"
strip     "no trailing newline"
keep      "keeps trailing blank lines\n\n"
single    "It's single-quoted, \\n stays as is"
double    "Tab:\tNewline:\nEnd"
empty_str ""

The Ruby heredoc is <<~'YAML' (quoted), so Ruby doesn't process the backslashes and YAML sees \n and \t as written. Block scalars are the cleanest way to embed shell scripts, SQL or templates in YAML, because nothing inside them needs escaping.

Multiple documents in one stream

--- starts a new document and ... optionally ends one. Kubernetes manifests and log files often put many documents in one file:

# Kubernetes-style file with three documents
kind: Service
metadata: {name: web}
---
kind: Deployment
metadata: {name: web}
spec: {replicas: 3}
---
kind: ConfigMap
metadata: {name: web-env}
data: {LOG_LEVEL: info}
...

YAML.load silently returns only the first document. Use safe_load_stream to get all of them:

require 'yaml'

text = File.read('manifests.yml')

p YAML.load(text)['kind']

docs = YAML.safe_load_stream(text, filename: 'manifests.yml')
p docs.size
docs.each { |d| puts "#{d['kind']}/#{d.dig('metadata', 'name')}" }

puts YAML.dump_stream({ 'kind' => 'Namespace' }, { 'kind' => 'Secret' })
"Service"
3
Service/web
Deployment/web
ConfigMap/web-env
---
kind: Namespace
---
kind: Secret

Watch out for YAML.load_stream: unlike YAML.load, it is not restricted. It builds any object a tag asks for:

require 'yaml'

class Foo; attr_accessor :a; end

p YAML.load_stream("--- !ruby/object:Foo\na: 1\n--- :sym\n")
begin
  YAML.safe_load_stream("--- !ruby/object:Foo\na: 1\n")
rescue Psych::DisallowedClass => e
  puts "#{e.class}: #{e.message}"
end
[#<Foo:0x000001b912fe76e0 @a=1>, :sym]
Psych::DisallowedClass: Tried to load unspecified class: Foo

safe_load_stream (psych 5.2+) accepts permitted_classes: and aliases:. It parses the whole input before returning, even when you pass a block. For true streaming see "Streaming large inputs" below.

Emitting YAML

YAML.dump(obj) and obj.to_yaml produce a document. Psych quotes strings that would otherwise load back as something else, and uses a | block for multi-line strings:

require 'yaml'

data = {
  'name' => 'Bookshelf',
  'version' => '1.10',
  'zip' => '01234',
  'country' => 'NO',
  'empty' => '',
  'nothing' => nil,
  'colon' => 'a: b',
  'hash_sign' => '#1 fan',
  'leading_space' => ' padded',
  'notes' => "line one\nline two\n",
  'tags' => %w[ruby yaml],
  'nested' => { 'list' => [{ 'id' => 1 }, { 'id' => 2 }], 'none' => [] }
}
puts data.to_yaml
---
name: Bookshelf
version: '1.10'
zip: '01234'
country: 'NO'
empty: ''
nothing:
colon: 'a: b'
hash_sign: "#1 fan"
leading_space: " padded"
notes: |
  line one
  line two
tags:
- ruby
- yaml
nested:
  list:
  - id: 1
  - id: 2
  none: []

Sequences inside a mapping are not indented (- ruby lines up with tags:). Both styles are valid YAML.

Dump options

require 'yaml'

config = { name: 'app', mode: :fast, db: { pool: 5 } }
puts YAML.dump(config)
puts YAML.dump(config, stringify_names: true)

doc = { 'description' => 'word ' * 18, 'db' => { 'replicas' => { 'count' => 2 } } }
puts YAML.dump(doc)
puts YAML.dump(doc, line_width: -1, indentation: 4)
---
:name: app
:mode: :fast
:db:
  :pool: 5
---
name: app
mode: :fast
db:
  pool: 5
---
description: 'word word word word word word word word word word word word word word
  word word word word '
db:
  replicas:
    count: 2
---
description: 'word word word word word word word word word word word word word word word word word word '
db:
    replicas:
        count: 2

When the options are the last arguments, wrap a literal hash in braces: YAML.dump({ 'a' => 1 }, line_width: -1). Without the braces Ruby merges line_width: into the data hash.

Shared objects become aliases

If the same object appears twice, Psych writes it once with an anchor and refers to it with an alias. The default loader then refuses the file:

require 'yaml'

defaults = { 'retries' => 3, 'timeout' => 5 }
jobs = { 'mailer' => defaults, 'indexer' => defaults }  # same Hash object twice

text = YAML.dump(jobs)
puts text
begin
  YAML.load(text)
rescue Psych::AliasesNotEnabled => e
  puts e.class
end
p YAML.load(text, aliases: true)

# dup the shared parts before dumping
puts YAML.dump(jobs.transform_values(&:dup))
---
mailer: &1
  retries: 3
  timeout: 5
indexer: *1
Psych::AliasesNotEnabled
{"mailer" => {"retries" => 3, "timeout" => 5}, "indexer" => {"retries" => 3, "timeout" => 5}}
---
mailer:
  retries: 3
  timeout: 5
indexer:
  retries: 3
  timeout: 5

safe_dump

YAML.safe_dump is the mirror of safe_load: it refuses to write anything that safe_load couldn't read back, so a stray object doesn't end up in a file as a !ruby/object tag:

require 'yaml'

puts YAML.safe_dump({ 'name' => 'app', 'ports' => [80, 443] })
puts YAML.safe_dump({ name: 'app', mode: :fast }, permitted_classes: [Symbol], stringify_names: true)

begin
  YAML.safe_dump({ 'when' => Time.now })
rescue Psych::DisallowedClass => e
  puts "#{e.class}: #{e.message}"
end

a = [1]
begin
  YAML.safe_dump({ 'x' => a, 'y' => a })
rescue Psych::BadAlias => e
  puts "#{e.class}: #{e.message}"
end
puts YAML.safe_dump({ 'x' => a, 'y' => a }, aliases: true)
---
name: app
ports:
- 80
- 443
---
name: app
mode: :fast
Psych::DisallowedClass: Tried to dump unspecified class: Time
Psych::BadAlias: Tried to dump an aliased object
---
x: &1
- 1
"y": *1

Note "y": the emitter quotes y and n because YAML 1.1 parsers in other languages read them as booleans.

Round-tripping loses formatting

Loading and dumping again throws away comments, flow style, block scalar style and the original spelling of values:

require 'yaml'

original = <<~YAML
  # Service settings
  port: 4567       # HTTP port
  debug: yes
  hosts: [a, b]
  greeting: >
    Hello
    world
YAML

data = YAML.safe_load(original)
data['port'] = 8080
puts YAML.dump(data)
---
port: 8080
debug: true
hosts:
- a
- b
greeting: 'Hello world

  '

Don't rewrite files that people edit by hand. If a program has to change one value in such a file, edit the text (for example with a regexp anchored on the key), or keep machine-written settings in a separate file.

Custom types

YAML.dump can write any object. Plain objects get a !ruby/object: tag with their instance variables, Structs get !ruby/struct: and Data objects get !ruby/data::

require 'yaml'

class Point
  attr_reader :x, :y
  def initialize(x, y) = (@x, @y = x, y)
  def inspect = "#<Point #{x},#{y}>"
end

Color = Struct.new(:r, :g, :b)
Size = Data.define(:w, :h)

shapes = { 'origin' => Point.new(0, 0), 'fill' => Color.new(255, 0, 0), 'size' => Size.new(w: 3, h: 4) }
text = YAML.dump(shapes)
puts text

begin
  YAML.load(text)
rescue Psych::DisallowedClass => e
  puts e.message
end

loaded = YAML.load(text, permitted_classes: [Point, Color, Size, Symbol])
p loaded['origin']
p loaded['fill']
p loaded['size']
---
origin: !ruby/object:Point
  x: 0
  y: 0
fill: !ruby/struct:Color
  r: 255
  g: 0
  b: 0
size: !ruby/data:Size
  w: 3
  h: 4
Tried to load unspecified class: Point
#<Point 0,0>
#<struct Color r=255, g=0, b=0>
#<data Size w=3, h=4>

Struct and Data members are Symbols internally, so loading them also needs Symbol in permitted_classes:. Loading builds objects without calling initialize, so validation in the constructor is skipped.

These tags only make sense to Ruby, and they tie the file to your class names. For data shared with other programs, or stored for a long time, convert to a Hash with to_h before dumping and rebuild the object explicitly after a safe load.

encode_with and init_with

To control what gets written, define encode_with(coder). YAML.load then calls init_with(coder) instead of setting instance variables directly:

require 'yaml'

class User
  attr_reader :name, :email, :password_hash, :cache

  def initialize(name, email, password_hash)
    @name, @email, @password_hash = name, email, password_hash
    @cache = {} # derived state we don't want to save
  end

  # called by YAML.dump: choose what gets written
  def encode_with(coder)
    coder['name'] = @name
    coder['email'] = @email
  end

  # called by YAML.load instead of initialize
  def init_with(coder)
    @name = coder['name']
    @email = coder['email']
    @password_hash = nil
    @cache = {}
  end
end

text = YAML.dump(User.new('alice', 'alice@example.com', '$2a$12$abc'))
puts text
u = YAML.load(text, permitted_classes: [User])
p [u.name, u.email, u.password_hash, u.cache]
--- !ruby/object:User
name: alice
email: alice@example.com
["alice", "alice@example.com", nil, {}]

Your own tags

A Psych::Coder can also represent an object as a scalar or a sequence with any tag. YAML.add_tag maps the tag back to the class when loading. This gives compact, readable values such as !money 19.90 EUR:

require 'yaml'
require 'bigdecimal'

class Money
  attr_reader :amount, :currency

  def initialize(amount, currency)
    @amount, @currency = BigDecimal(amount), currency
  end

  def to_s = format('%.2f %s', amount, currency)

  def encode_with(coder)
    coder.represent_scalar('!money', to_s)
  end

  def init_with(coder)
    amount, @currency = coder.scalar.split
    @amount = BigDecimal(amount)
  end
end

YAML.add_tag('!money', Money)

order = { 'id' => 42, 'total' => Money.new('19.90', 'EUR'), 'shipping' => Money.new('4.5', 'EUR') }
puts YAML.dump(order)

doc = <<~YAML
  price: !money 7.25 USD
  tax: !money 0.58 USD
YAML
prices = YAML.safe_load(doc, permitted_classes: [Money])
prices.each { |k, v| puts "#{k}: #{v} (#{v.amount.class})" }
puts "sum: #{prices.values.sum(&:amount).to_s('F')}"

begin
  YAML.safe_load(doc)
rescue Psych::DisallowedClass => e
  puts e.message
end
---
id: 42
total: !money 19.90 EUR
shipping: !money 4.50 EUR
price: 7.25 USD (BigDecimal)
tax: 0.58 USD (BigDecimal)
sum: 7.83
Tried to load unspecified class: Money

A registered tag is still subject to the safe loader: the class has to be in permitted_classes:. coder.represent_seq(tag, array) and coder.represent_map(tag, hash) work the same way for collections.

The node tree

Psych.parse returns the document as a tree of Psych::Nodes (Document, Mapping, Sequence, Scalar, Alias) without converting anything to Ruby objects. That's useful for YAML written for other tools. AWS CloudFormation, for example, uses tags such as !Ref and !Sub, which the safe loader quietly drops:

require 'yaml'

template = <<~YAML
  Resources:
    Bucket:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: !Sub "${AWS::StackName}-logs"
        Tags: !Ref CommonTags
YAML

p YAML.safe_load(template).dig('Resources', 'Bucket', 'Properties')

ast = Psych.parse(template)       # Psych::Nodes::Document
p ast.class
p ast.root.class

tagged = ast.each.select { |n| n.respond_to?(:tag) && n.tag }
tagged.each { |n| puts "#{n.tag} #{n.value.inspect} (line #{n.start_line + 1})" }
{"BucketName" => "${AWS::StackName}-logs", "Tags" => "CommonTags"}
Psych::Nodes::Document
Psych::Nodes::Mapping
!Sub "${AWS::StackName}-logs" (line 5)
!Ref "CommonTags" (line 6)

each walks every node depth-first, and each node knows its start and end line and column, which is handy for linters that report positions.

The tree also gives you control over output style, which YAML.dump doesn't offer. Dump, parse into a tree, change node styles, and emit with to_yaml:

require 'yaml'

data = {
  'name' => 'web',
  'ports' => [80, 443],
  'env' => { 'LOG_LEVEL' => 'info' },
  'command' => ['bundle', 'exec', 'puma']
}

tree = Psych.parse_stream(YAML.dump(data))
tree.each do |node|
  case node
  when Psych::Nodes::Sequence
    # short lists of scalars read better as [a, b, c]
    node.style = Psych::Nodes::Sequence::FLOW if node.children.all?(Psych::Nodes::Scalar)
  when Psych::Nodes::Scalar
    if node.value == 'info'
      node.style = Psych::Nodes::Scalar::DOUBLE_QUOTED
      node.quoted = true # otherwise Psych adds a '!' tag to keep the type
    end
  end
end
puts tree.to_yaml
---
name: web
ports: [80, 443]
env:
  LOG_LEVEL: "info"
command: [bundle, exec, puma]

Streaming large inputs

YAML.load builds the whole node tree and then the whole Ruby object graph in memory. For large inputs Psych offers two lower-level APIs.

One document at a time

Psych.parse_stream with a block reads from an IO and yields each document's node tree as soon as the document ends, so a file with millions of small documents (a log, an export) never sits in memory at once. To convert each node safely, wrap it in a stream and pass it through safe_load. That's exactly what safe_load_stream does internally, but here it happens per document:

require 'yaml'

def each_safe_document(io)
  return enum_for(__method__, io) unless block_given?

  Psych.parse_stream(io, filename: io.respond_to?(:path) ? io.path : nil) do |doc_node|
    stream = Psych::Nodes::Stream.new
    stream.children << doc_node
    yield YAML.safe_load(stream.to_yaml)
  end
end

errors = 0
count = 0
File.open('events.yml') do |f|
  each_safe_document(f) do |event|
    count += 1
    errors += 1 if event['type'] == 'error'
  end
end
puts "#{count} events, #{errors} errors"

File.open('events.yml') { |f| p each_safe_document(f).first(2) }
100000 events, 10000 errors
[{"id" => 0, "type" => "error", "msg" => "event 0"}, {"id" => 1, "type" => "info", "msg" => "event 1"}]

events.yml is 4.5 MB of documents like { 'id' => 0, 'type' => 'error', 'msg' => 'event 0' }.to_yaml written one after another. Appending documents with to_yaml (each starts with ---) is a simple way to write such a file. Because the method returns an Enumerator without a block, first(2) stops parsing after two documents.

Events with Psych::Handler

When even one document is too big, use the event parser. Psych::Parser reads the input and calls methods on a Psych::Handler subclass for each event; nothing is kept unless your handler keeps it:

require 'yaml'

# Prints every event the parser emits
class Tracer < Psych::Handler
  def initialize = @depth = 0
  def start_document(version, tags, implicit) = log("start_document")
  def end_document(implicit)                  = log("end_document")
  def start_mapping(anchor, tag, implicit, style)
    log("start_mapping")
    @depth += 1
  end
  def end_mapping
    @depth -= 1
    log("end_mapping")
  end
  def start_sequence(anchor, tag, implicit, style)
    log("start_sequence")
    @depth += 1
  end
  def end_sequence
    @depth -= 1
    log("end_sequence")
  end
  def scalar(value, anchor, tag, plain, quoted, style) = log("scalar #{value.inspect}")
  def log(msg) = puts("#{'  ' * @depth}#{msg}")
end

Psych::Parser.new(Tracer.new).parse("name: app\nports: [80, 443]\n")
start_document
start_mapping
  scalar "name"
  scalar "app"
  scalar "ports"
  start_sequence
    scalar "80"
    scalar "443"
  end_sequence
end_mapping
end_document

Scalars arrive as raw Strings ("80", not 80): typing happens later, in the tree-to-Ruby step. Inside a mapping, scalars alternate between key and value, so a handler has to track that itself. This one collects every email: value from a single 13 MB document with 200,000 users:

require 'yaml'

# Collects the value of every `email:` key, without building the document
class EmailCollector < Psych::Handler
  attr_reader :emails

  def initialize
    @emails = []
    @stack = []    # one entry per open mapping/sequence
  end

  def start_mapping(*)  = push(:map)
  def start_sequence(*) = push(:seq)
  def end_mapping       = @stack.pop
  def end_sequence      = @stack.pop

  def scalar(value, *)
    top = @stack.last
    if top.is_a?(Hash) # inside a mapping: scalars alternate key, value
      if top[:key].nil?
        top[:key] = value
      else
        @emails << value if top[:key] == 'email'
        top[:key] = nil
      end
    end
  end

  private

  def push(kind)
    # a nested collection is a value: reset the parent's pending key
    @stack.last[:key] = nil if @stack.last.is_a?(Hash)
    @stack << (kind == :map ? { key: nil } : :seq)
  end
end

t = Process.clock_gettime(Process::CLOCK_MONOTONIC)
handler = EmailCollector.new
File.open('users.yml') { |f| Psych::Parser.new(handler).parse(f) }
puts "events: #{handler.emails.size} emails in %.2fs" % (Process.clock_gettime(Process::CLOCK_MONOTONIC) - t)
p handler.emails.first(2)

t = Process.clock_gettime(Process::CLOCK_MONOTONIC)
emails = YAML.load_file('users.yml')['users'].map { _1['email'] }
puts "load_file: #{emails.size} emails in %.2fs" % (Process.clock_gettime(Process::CLOCK_MONOTONIC) - t)
events: 200000 emails in 1.08s
["user0@example.com", "user1@example.com"]
load_file: 200000 emails in 2.41s

The event parser was more than twice as fast here (timings vary between runs) and its memory use stays flat, while load_file holds the full tree and every object at once. Psych is not a fast YAML parser in general; for big data sets that you control, JSON or a line-based format such as JSON Lines is much quicker to read.

YAML::Store

yaml/store gives you a small persistent key-value store with transactions, built on PStore but saving human-readable YAML:

require 'yaml/store'

store = YAML::Store.new('counters.yml')
3.times do
  store.transaction do
    store['runs'] = store.fetch('runs', 0) + 1
    store['last'] = 'ok'
  end
end
store.transaction(true) { p store['runs'] } # read-only
puts File.read('counters.yml')
3
---
runs: 3
last: ok

Each transaction reads and rewrites the whole file under a file lock, so it suits small amounts of data such as tool state or counters, not a database.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents