Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are strings beginning with a space converted with: ! ' with Ruby/YAML

Tags:

ruby

yaml

I am writing a Ruby hash to a file using YAML.

File.open(output_file, "w") {|file| file.puts YAML::dump(final)}

The hash contains strings as keys and floats as values.

When my strings contain only letter they are outputted as such in the file file:

abc: 1.0
bcd: 1.0
cde: 1.0

When a string starts with a space it is outputted as such:

! ' ab': 1.0

When I read the file back in again everything is ok, but I want to know why this is happening and what does it mean.

I searched the YAML documentation and it says that a single exclamation point is used to represent local datatypes.

Why does this happen on string starting with spaces?

like image 293
Gilles Avatar asked Dec 09 '12 19:12

Gilles


1 Answers

The ! is known as the "non-specific tag". It forces the YAML engine to decode the following item as either a string, a hash, or an array. It basically disables interpreting it as a different type. I'm not sure why the engine is tagging them this way; it doesn't seem to be needed. Perhaps it is just overzealously attempting to remove ambiguity?

Edit: either way, it's unneeded syntax:

YAML.dump({' a'=>0})
=> "---\n! ' a': 0\n"
YAML.load("---\n! ' a': 0\n") # with the bang
=> {" a"=>0}
YAML.load("---\n' a': 0\n")   # without the bang
=> {" a"=>0}
like image 140
marcus erronius Avatar answered Oct 01 '22 06:10

marcus erronius