Dorian Dorian - 19 days ago 8
Ruby Question

Concatenation of YAML "anchors" with another string in keys

So I want to turn this:

a:
b: &b "hello"
c: *b "world"


Into this:
{"a"=>{"b"=>"hello", "c"=>"hello world"}}


But right now I get
did not find expected key while parsing a block mapping at line 2 column 3
.

I know that this works fine:

a:
b: &b "hello"
c: *b


(I learned from learnxinyminutes and also tries some
%() %{} #{} ..
syntaxes but none of them worked)

Answer

YAML is not a programming language and in general does not provide the tool for doing what you want.

However, if you really want to do something like this, nothing hinders you from defining some tag !concat and implement it in a way that lets you do

a:
  b: &b "hello"
  c: !concat [*b, "world"]

The important thing is: You need to implement this yourself on the loading side. And that idea is not too exotic; there is a (non-standard) definition for a !!merge tag which does similar things to mappings here, and some YAML implementations support that. But it did not find its way into the standard for good reasons. Rule of thumb: If you want to do something like this, YAML is probably not the right tool for you.

Comments