4

I've been told that depending on the YAML library used, when a list (not hash!) in a YAML file is translated into a Ruby array, the order is not guaranteed. However, I've not been able to find any evidence of this. So given a YAML file like:

letters:
- a
- b
- c
- d
- e

After doing YAML::load File.read('filename'), I'm always guaranteed to get {'letters'=>['a', 'b', 'c', 'd', 'e']}, instead of some other ordering, regardless of which YAML library I'm using, correct?

Suan
  • 34,563
  • 13
  • 47
  • 61

2 Answers2

3

Yes, order of a sequence is guaranteed. From the spec discussion of unordered mappings:

In every case where node order is significant, a sequence must be used.

pilcrow
  • 56,591
  • 13
  • 94
  • 135
1

I can't speak for the Ruby YAML implementation but a "list" is, by definition, "an ordered collection of values".

And, a YAML list is indeed defined in this way;

letters:
- a
- b
- c
- d
- e

A quick test;

require 'yaml'

results = Array.new(1_000) do
  YAML.load("letters:\n- a\n- b\n- c\n- d\n- e")
end

puts results.uniq

Seems pretty safe that it will always be ordered!

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Matthew Rudy
  • 16,724
  • 3
  • 46
  • 44