How to keep hash sort from YAML

how can I cast a YAML hash data into a ruby obj without
any auto-sort feature?

···

---
2: 1
1: 2
3: 3

=> {1=> 2, 2=>1, 3=>3} # no, thanks
=> {2=> 1, 1=>2, 3=>3} # yes!

tnx!

--

here are more things in heaven and earth,

horatio, than are dreamt of in your philosophy.

Hashes are unordered by definition. You have no control over how Ruby stores and returns the pairs. If you need an ordered data structure, use an Array.

Hope that helps.

James Edward Gray II

···

On May 14, 2005, at 3:26 PM, dave wrote:

how can I cast a YAML hash data into a ruby obj without
any auto-sort feature?
---
2: 1
1: 2
3: 3

=> {1=> 2, 2=>1, 3=>3} # no, thanks
=> {2=> 1, 1=>2, 3=>3} # yes!

dave wrote:

how can I cast a YAML hash data into a ruby obj without
any auto-sort feature?
---
2: 1
1: 2
3: 3

James is correct. Neither Ruby nor YAML allows hashes to be ordered. However, Ruby's YAML library includes an Omap type[1], which acts like the ordered dictionaries you'll find in PHP.

A basic demonstration:

  >> require 'yaml'
  => true
  >> omap = YAML::Omap['c', 1, 'a', 2, 'b', 3]
  => [["c", 1], ["a", 2], ["b", 3]]
  >> y omap
  --- !omap
  - c: 1
  - a: 2
  - b: 3

As you can see, the Omap is just an array that contains hash pairs. You can use the Omap in Ruby just like a Hash.

  >> omap2 = YAML::load( YAML::dump( omap ) )
  => [["c", 1], ["a", 2], ["b", 3]]
  >> omap2.each { |k,v| p [k,v] }
  ["c", 1]
  ["a", 2]
  ["b", 3]

_why
[1] Ordered Mapping Language-Independent Type for YAML™ Version 1.1

Hashes are unordered by definition.
You have no control over how
Ruby stores and returns the pairs.

I would report to the user hashes in the same order they were
written in yaml by the user.

If you need an ordered data structure, use an Array.

I must handle hashes too.

···

--

here are more things in heaven and earth,

horatio, than are dreamt of in your philosophy.

As you can see, the Omap is just an array that contains hash pairs. You
can use the Omap in Ruby just like a Hash.

thank you all, i'm now able to better understand the problem (and the
solution).

···

--

here are more things in heaven and earth,

horatio, than are dreamt of in your philosophy.