how to keep hash sort from YAML

D

dave

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.
 
J

James Edward Gray II

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!

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
 
D

dave

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

I would report to the user hashes in the same order they were=20
written in yaml by the user.
If you need an ordered data structure, use an Array.

I must handle hashes too.


=2D-=20
here are more things in heaven and earth,
horatio, than are dreamt of in your philosophy.
 
W

why the lucky stiff

dave said:
how can I cast a YAML hash data into a ruby obj without
any auto-sort feature?
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] http://yaml.org/type/omap.html
 
D

dave

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

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

=2D-=20
here are more things in heaven and earth,
horatio, than are dreamt of in your philosophy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,591
Members
45,103
Latest member
VinaykumarnNevatia
Top