Afficher un hash dans l’ordre en Ruby

Ruby, contrairement à PHP (mais comme beaucoup d’autres langages), fait la différence entre un tableau (avec des index numériques) et un hash (avec n’importe quel type d’index, mais sans notion d’ordre). Etant habitué à PHP, je me suis heurté au problème suivant : comment afficher un hash dans l’ordre ?

Considerons le code suivant, où le hash contient les éléments indexés par leur id numérique (je n’utilise pas un tableau volontairement, car j’ai besoin de ces id).

hash = {
	1 => "toto",
	2 => "tata",
	3 => "titi",
	4 => "tutu",
	5 => "tete",
	6 => "tyty"
}

hash.each_pair do |key, value|
	puts "#{key} = #{value}"
end

Il va afficher :

5 = tete
6 = tyty
1 = toto
2 = tata
3 = titi
4 = tutu

Ce résultat correspond à la documentation de la classe Hash :

A Hash is a collection of key-value pairs. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index. The order in which you traverse a hash by either key or value may seem arbitrary, and will generally not be in the insertion order.

Bref, c’est tout à fait normal, mais pas du tout ce que je recherche. Pour l’afficher dans l’ordre, il suffit en fait de trier et parcourir les clefs du hash :

hash.keys.sort!.each do |key|
	puts "#{key} = " + hash[key]
end

Et on obtient le bon ordre :

1 = toto
2 = tata
3 = titi
4 = tutu
5 = tete
6 = tyty

Youpi ! Bon, on peut toujours critiquer PHP, mais son concept de tableau/hash mélangé et ordonné, c’est quand même bien pratique :-)

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!