2009-09-10 7 views
4

J'ai un tableau de Products, chacun ayant un nom et une catégorie. Je voudrais produire un hachage dans lequel chaque clé est une chaîne de catégorie et chaque élément est un produit avec cette catégorie, semblable à ce qui suit:Réorganisation du tableau Ruby en hachage

{ "Apple" => [ <Golden Delicious>, <Granny Smith> ], ... 
    "Banana" => ... 

Est-ce possible?

Répondre

3
h = Hash.new {|h, k| h[k] = []} 
products.each {|p| h[p.category] << p} 
8

En 1.8.7+ ou avec active_support (ou facettes, je pense), vous pouvez utiliser group_by:

products.group_by {|prod| prod.category} 
0
# a for all 
# p for product 
new_array = products.inject({}) {|a,p| a[p.category.name] ||= []; a[p.category.name] << p} 
+0

Il vous manque "; a" à la fin de votre bloc d'injection - le bloc doit renvoyer le hash de mémo. –

+0

merci pour la note! mais ne pas la dernière expression renvoie le hachage? – Eimantas

+0

Non, il renvoie le tableau a [p.category.name] (résultat de la méthode Array # <<) –

1

Le oneliner

arr = [["apple", "granny"],["apple", "smith"], ["banana", "chiq"]] 
h = arr.inject(Hash.new {|h,k| h[k]=[]}) {|ha,(cat,name)| ha[cat] << name; ha} 

:-)

Mais je suis d'accord, #group_by est beaucoup plus élégant.

Questions connexes