Nếu bạn muốn để đối phó một cách chính xác với giá trị nhân bản, sau đó bạn nên sử dụng Hash # inverse từ Facets of Ruby
Hash#inverse
duy trì các giá trị trùng lặp, ví dụ:nó đảm bảo rằng hash.inverse.inverse == hash
một trong hai:
sử dụng 'mặt' như thế này :
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}
Mã này trông như thế này:
# 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}
Tôi không chắc chắn cách làm cho nó in ra một mảng để tôi có thể đọc nó để thử nghiệm. – cjm2671
Tuy nhiên, bạn đã thử những gì? 'p mảng' in ra. – Mat
Bạn có chắc chắn đó là một mảng chứ không phải là một băm? Cách bạn mô tả nó là mơ hồ. –