Examples

This page contains all of the examples from throughout this documentation. Convenient? Perhaps?

- dogs
- cats
- badgers
Ex. 1: Simple sequence in YAML
[ 'dogs', 'cats', 'badgers' ]
Ex. 2: Simple sequence in Ruby
require 'yaml'
puts( [ 'dogs', 'cats', 'badgers' ].to_yaml )
# prints:
#   - dogs
#   - cats
#   - badgers
Ex. 3: Using to_yaml to output a sequence
- 
  - pineapple
  - coconut
-
  - umbrella
  - raincoat
Ex. 4: Nested sequence in YAML
dog: canine
cat: feline
badger: malign
Ex. 5: Simple mapping in YAML
{ 'dog' => 'canine',
  'cat' => 'feline',
  'badger' => 'malign' }
Ex. 6: Simple mapping in Ruby
require 'yaml'
puts( { 'dog' => 'canine',
        'cat' => 'feline',
        'badger' => 'malign' }.to_yaml )
# prints:
#   dog: canine
#   cat: feline
#   badger: malign
Ex. 7: Using to_yaml to output a mapping
Joey:
  age: 22
  sex: M
Laura:
  age: 24
  sex: F
Ex. 8: Nested mapping
- ~
- true
- 10
- 10.2
- 2002-08-15T17:18:23.18-06:00
- 2002-08-15
Ex. 9: Basic types in YAML
~: NilClass
+: TrueClass
true: TrueClass
True: TrueClass
-: FalseClass
false: FalseClass
False: FalseClass
0: Integer
1: Integer
100: Integer
1,000: Integer
0.0: Float
1.0: Float
100.001: Float
1,000.001: Float
1.00009e+3: Float
2002-08-15T17:18:23.18-06:00: Time
2002-08-15 17:18:23.18 -06:00: Time
1976-07-31: Date
Ex. 10: Basic types and their Ruby classes
puts( nil.to_yaml )
# prints:
#   --- ~

puts( true.to_yaml )
# prints:
#   --- true

puts( false.to_yaml )
# prints:
#   --- (false)

puts( 10.to_yaml )
# prints: 
#   --- 10

puts( 20.45.to_yaml )
# prints:
#   --- 20.45

puts( Time.now.to_yaml )
# prints:
#   --- 2002-08-15T17:29:01.79-06:00

puts( Date.new( 1976, 07, 31 ).to_yaml )
# prints:
#   --- 1976-07-31
Ex. 11: Using to_yaml with basic types
- literal: |
    A literal block keeps all
    new lines when it is brought
    into Ruby.
- folded: >
    A folded block will get rid
    of its newlines, trading them
    for spaces when it is brought
    into Ruby.
Ex. 12: Literal and folded blocks
txt = "Just got my (dead-tree, printed-on-paper, I don't know if there's a web " +
      "version) copy of Linux Magazine for September, 2002.  There's an article by " +
      "Dave Thomas about building networked applications in Ruby.\n\nProps to Dave!"

puts txt.to_yaml
# prints:
#   --- >-
#   Just got my (dead-tree, printed-on-paper, I don't know if there's a web version)
#   copy of Linux Magazine for September, 2002.  There's an article by Dave Thomas
#   about building networked applications in Ruby.
#   
#   
#   Props to Dave!
Ex. 13: Case where to_yaml generates a folded block
txt =<<EOF

ZenWeb 2.11.0 has been released!

I don't think I've remembered to announce any releases in a while, so
this one is a tad different. Among the newest changes are:

  + relative url renderer
  + massively improved demo/docs

:)
EOF

puts txt.to_yaml
# prints:
#   --- |
#   
#   ZenWeb 2.11.0 has been released!
#   
#   I don't think I've remembered to announce any releases in a while, so
#   this one is a tad different. Among the newest changes are:
#   
#     + relative url renderer
#     + massively improved demo/docs
#   
#   :)
#
Ex. 14: Case where to_yaml generates a literal block
simple symbol: !ruby/symbol Simple
shortcut syntax: !ruby/sym Simple
symbols in maps:
  !ruby/sym MapKey: !ruby/sym MapValue
Ex. 15: Symbols in YAML
puts :Simple.to_yaml
# prints:
#   --- !ruby/sym Simple
Ex. 16: Using to_yaml with Symbols
normal range: !ruby/range 10..20
exclusive range: !ruby/range 11...20
negative range: !ruby/range -1..-5
? !ruby/range 0..40
: range as a map key
Ex. 17: Ranges in YAML
floats: !ruby/range 10.2..21.5
dates: !ruby/range 2001-03-02..2001-09-11
timestamps: !ruby/range 2001-09-03T05:16:23Z..2001-09-04T07:08:13Z
Ex. 18: Other basic types in Ranges
starts with a b: !ruby/regexp '/^b/'
ends with a z: !ruby/regexp '/z$/'
search for a C or c: !ruby/regexp '/c/i'
Ex. 19: Regexps in YAML
puts( /^b/.to_yaml )
# prints:
#   --- !ruby/regexp "/^b/"
Ex. 20: Using to_yaml with Regexps
class Video
  attr_accessor :title, :year, :rating
  def initialize( t, y, r )
    @title = t
    @year = y
    @rating = r
  end
end
Ex. 21: Video class
collection = [ 
  Video.new( "Ishtar", 1987, 8.8 ),
  Video.new( "Dr. Strangelove", 1964, 10.0 )
]
Ex. 22: Your Video collection
puts collection.to_yaml
# prints:
#   - !ruby/object:Video
#     title: Ishtar
#     year: 1987
#     rating: 8.8
#   - !ruby/object:Video
#     title: Dr. Strangelove
#     year: 1964
#     rating: 10.0
Ex. 23: Your Videos in YAML
puts [[ 'Crispin', 'Glover' ]].to_yaml( :Indent => 4, :UseHeader => true, :UseVersion => true )
# prints:
#   --- %YAML:1.0
#   -
#       - Crispin
#       - Glover
Ex. 24: Using to_yaml with an options Hash
Indent: The default indentation to use when emitting (defaults to 2)
Separator: The default separator to use between documents (defaults to '---')
SortKeys: Sort Hash keys when emitting? (defaults to false) 
UseHeader: Display the YAML header when emitting? (defaults to false)
UseVersion: Display the YAML version when emitting? (defaults to false)
AnchorFormat: A formatting string for anchor IDs when emitting (defaults to 'id%03d')
ExplicitTypes: Use explicit types when emitting? (defaults to false)
BestWidth: The character width to use when folding text (defaults to 80)
UseFold: Force folding of text when emitting? (defaults to false)
UseBlock: Force all text to be literal when emitting? (defaults to false)
Encoding: Unicode format to encode with (defaults to :Utf8; requires Iconv)
Ex. 25: Available symbols for an options Hash
any Object#to_yaml method
YAML::Stream.new
YAML::Store.new
YAML::emitter_proc
Ex. 26: Methods which take an options Hash
require 'yaml'
y = YAML::Store.new( "/tmp/yaml.store.1", :Indent => 2 )
y.transaction do
  y['names'] = ['Crispin', 'Glover']
  y['hello'] = {'hi' => 'hello', 'yes' => 'YES!!' }
end
Ex. 27: Initializing YAML::Store
hello:
  hi: hello
  yes: YES!!
names:
  - Crispin
  - Glover
Ex. 28: Dump of /tmp/yaml.store.1
o = [ 'array', 'of', 'items' ]
o2 = YAML::load( o.to_yaml )
# o2 and o should be equal
Ex. 29: YAML::load, the answer to Object#to_yaml
node = YAML::parse( <<EOY )
one: 1
two: 2
EOY

puts node.type_id
# prints: 'map'

p node.value['one']
# prints key and value nodes: 
#   [ #<YAML::YamlNode:0x8220278 @type_id="str", @value="one", @kind="scalar">, 
#     #<YAML::YamlNode:0x821fcd8 @type_id="int", @value="1", @kind="scalar"> ]'

# Mappings can also be accessed for just the value by accessing as a Hash directly
p node['one']
# prints: #<YAML::YamlNode:0x821fcd8 @type_id="int", @value="1", @kind="scalar"> 
Ex. 30: YamlNode representing a root-level mapping
--- !rubyjunkies.com,2002-10-24/addressBook
name: Bunbury Olsen
phone: 801-090-0900
address: |
  12 E. 400 S.
  SLC, UT 84020
Ex. 31: Custom type family assigned to a domain
YAML.add_domain_type( "rubyjunkies.com,2002-10-24", "addressBook" ) { |type, val|
  # Do something with 'val' here
}
Ex. 32: Registering the address book type with YAML.add_domain_type
class AddressBook
  attr_accessor :name, :phone, :address
end

YAML.add_domain_type( "rubyjunkies.com,2002-10-24", "addressBook" ) { |type, val|
  YAML.object_maker( AddressBook, val )
}
Ex. 33: YAML.add_domain_type and YAML.object_maker
class AddressBook
  def to_yaml( opts = {} )
    YAML.quick_emit( self.id, opts ) { |out|
      out.map( "!rubyjunkies.com,2002-10-24" ) { |map|
        instance_variables.sort.each { |iv|
          map.add( iv[1..-1], instance_eval( iv ) )
        }
      }
    }
  end
end
Ex. 34: Overloading to_yaml for your type family
def to_yaml_type
  "!rubyjunkies.com,2002-10-24/addressBook"
end
Ex. 35: Quicker to_yaml_type for classes
def to_yaml_properties
  [ '@name', '@phone', '@address' ]
end
Ex. 36: Overloading to_yaml_properties
readme = YAML::load( File.open( 'README' ) )
Ex. 37: YAML::load Example
readme_doc = YAML::load_stream( File.open( 'README' ) )
puts readme_doc.documents[0]['title']
# prints:
#   YAML.rb
Ex. 38: YAML::load_stream Example
---
at: 2001-08-12 09:25:00.00 Z
type: GET
HTTP: '1.0'
url: '/index.html'
---
at: 2001-08-12 09:25:10.00 Z
type: GET
HTTP: '1.0'
url: '/toc.html'
Ex. 39: Stream containing a log file
require 'yaml'
log = File.open( "/var/log/apache.yaml" )
yp = YAML::load_documents( log ) { |doc|
  puts "#{doc['at']} #{doc['type']} #{doc['url']}"
}
Ex. 40: Loading the log file with YAML::load_documents
YAML::Parser.new.parse( io )
Ex. 41: YAML.load Source
d = YAML::Stream.new( :Indent => 4, :UseHeader => true )
d.add( 'one' )
d.add( 'two' )
d.add( 'three' )
puts d.emit
# prints:
#   --- one
#   --- two
#   --- three
Ex. 42: YAML::Stream.new
tree = YAML::parse( File.open( "README" ) )
puts tree.type_id
# prints:
#   map

title = tree.select( "/title" )[0]
puts title.value
# prints:
#   YAML.rb

obj_tree = tree.transform
puts obj_tree['title']
# prints:
#   YAML.rb
Ex. 43: Parsing a YAML document
require 'yaml'
log = File.open( "/var/log/apache.yaml" )
yp = YAML::parse_documents( log ) { |tree|
  at = tree.select('/at')[0].value
  type = tree.select('/type')[0].value
  puts "#{at} #{type}"
}
Ex. 44: Parsing YAML documents from a stream
players = YAML::parse( <<EOY )
  player:
    - given: Sammy
      family: Sosa
    - given: Ken
      family: Griffey
    - given: Mark
      family: McGwire
EOY

given = players.select( "/player/*/given" )
p given.transform
# prints:
#   ["Sammy", "Ken", "Mark"]
Ex. 45: Transforming the results of a YPath selection
YAML.add_domain_type( "hospital.com,2003", "Med" ) do |type, val|
  Medication.new( val )
end
Ex. 46: Adding a Domain Type