YAML Syntax - Scalars

Let's start with the basics: Scalars. Scalars are your bread and butter in YAML. They're the simplest type of data you can use, and they include strings, numbers, booleans, and null. Grab your keyboard, a cup of coffee, and let's explore this together.

Scalars (Strings, Numbers, Booleans, Null)

Single line Scalars

A scalar in YAML is a single data value that cannot be divided any further. When I say strings, numbers, booleans, and null, we are talking about scalars.

For example:

name: "Alice"
age: 25
is_developer: true
coffee_preference: null

In this example, "Alice" is a string scalar, 25 is a number scalar, true is a boolean scalar, and null is a special type of scalar that represents no value or the absence of a value.

Wait, did you see how we quoted "Alice", but not 25, true, or null? That's because in YAML, you don't need to quote strings unless they might be mistaken for another type of data (like true, false, null, or a number).

Now, I see that sparkle in your eyes, you're ready to create your own scalars. Go ahead and give it a shot!

Multiline Strings

Now, let's talk about something fun – multiline strings. Sometimes, you want to represent a text that spans multiple lines. That's where multiline strings come in.

There are two ways to do this in YAML:

Literal Style

The first is called the "literal style", and it keeps newlines and any trailing spaces. We use the pipe symbol | to indicate a literal string:

poem: |
  Roses are red
  Violets are blue
  YAML is sweet
  And so are you

Look at that lovely poem! The newlines and spaces are preserved exactly as they're written.

Folded Style

The second way to represent multiline strings is called the "folded style", which collapses newlines, but preserves them as spaces. We use the greater-than symbol > to denote a folded string:

speech: >
  Friends, Romans, countrymen,
  lend me your ears;
  I come to teach you YAML,
  not to overwhelm with fears.

Even though we wrote this on multiple lines, YAML will treat it like one single line with spaces where the newlines used to be.

Congratulations, my dear padawan! You're well on your way to becoming a YAML master. You've now learned about scalars and multiline strings. Practice what you've learned and keep exploring.

Remember, YAML is more of a friendly kitten than a ferocious beast. Embrace it, and it will serve you well.

Previous Next

Written © 2024 Written Developer Tutorials and Posts.

𝕏