Si usted quiere tratar correctamente con valores duplicados, a continuación, debe usar el Hash # inverso de Facets of Ruby
Hash#inverse
conserva los valores duplicados, p.asegura que hash.inverse.inverse == hash
ya sea:
como esto :
require 'facets'
h = {:key1 => [:a, :b, :c], :key2 => [:d, :e, :f]}
=> {:key1=>[:a, :b, :c], :key2=>[:d, :e, :f]}
h.inverse
=> {:a=>:key1, :b=>:key1, :c=>:key1, :d=>:key2, :e=>:key2, :f=>:key2}
El código es el siguiente:
# this doesn't looks quite as elegant as the other solutions here,
# but if you call inverse twice, it will preserve the elements of the original hash
# true inversion of Ruby Hash/preserves all elements in original hash
# e.g. hash.inverse.inverse ~ h
class Hash
def inverse
i = Hash.new
self.each_pair{ |k,v|
if (v.class == Array)
v.each{ |x|
i[x] = i.has_key?(x) ? [k,i[x]].flatten : k
}
else
i[v] = i.has_key?(v) ? [k,i[v]].flatten : k
end
}
return i
end
end
h = {:key1 => [:a, :b, :c], :key2 => [:d, :e, :f]}
=> {:key1=>[:a, :b, :c], :key2=>[:d, :e, :f]}
h.inverse
=> {:a=>:key1, :b=>:key1, :c=>:key1, :d=>:key2, :e=>:key2, :f=>:key2}
No estoy seguro de cómo imprimir una matriz para que pueda leerla y experimentar. – cjm2671
Aún así, ¿qué has intentado? 'p array' imprime cosas. – Mat
¿Estás seguro de que es una matriz y no un hash? La forma en que lo describes es ambigua. –