Si usted tiene un hash dónde están las llaves son únicos, puede utilizar Hash#invert:
> {a: 1, b: 2, c: 3}.invert
=> {1=>:a, 2=>:b, 3=>:c}
Eso no funcionará si tiene las claves no únicas, sin embargo, donde sólo los últimos teclas serán vistos mantienen:
> {a: 1, b: 2, c: 3, d: 3, e: 2, f: 1}.invert
=> {1=>:f, 2=>:e, 3=>:d}
Si usted tiene un hash con claves no únicas, que podría hacer:
> hash={a: 1, b: 2, c: 3, d: 3, e: 2, f: 1}
> hash.each_with_object(Hash.new { |h,k| h[k]=[] }) {|(k,v), h|
h[v] << k
}
=> {1=>[:a, :f], 2=>[:b, :e], 3=>[:c, :d]}
Si los valores del hash ya son matrices, puede hacerlo:
> hash={ "A" => [14, 15, 16], "B" => [17, 15], "C" => [35, 15] }
> hash.each_with_object(Hash.new { |h,k| h[k]=[] }) {|(k,v), h|
v.map {|t| h[t] << k}
}
=> {14=>["A"], 15=>["A", "B", "C"], 16=>["A"], 17=>["B"], 35=>["C"]}
¡Muy relevante! Gracias por señalar, no probé esos casos. –
['each_with_object'] (http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-each_with_object) tiene más sentido aquí que' inject'. –
de modo que se convierta en 'each_with_object ({}) {| i, o | k, v = * i; o [v] || = []; o [v] << k} '... agradable –