class Hash
def hash_revert
hash_new = Hash.new
self.each {|key,value|
if not hash_new.has_key?(key) then hash_new[value] = key end
}
return hash_new
end
end
h = {2=>βaβ, 1=> βbβ, 3 =>βaβ, 4=> βaβ, 5 => βbβ, 6=>βcβ}
p h.hash_revert #β> {βaβ=>4, βbβ=>1, βcβ=>6}
class Hash
def hash_revert
hash_new = Hash.new
self.each {|key,value|
if not hash_new.has_key?(key) then hash_new[value] = key end
}
return hash_new
end
end
h = {2=>βaβ, 1=> βbβ, 3 =>βaβ, 4=> βaβ, 5 => βbβ, 6=>βcβ}
p h.hash_revert #β> {βaβ=>4, βbβ=>1, βcβ=>6}
or Should I get this ??
=> {βaβ=>2, βbβ=>1, βcβ=>6}
Because HASH is working like βSetβ ??
many thanks in advance,
salai.
In Ruby 1.9, hashes keep the order of input. Before Ruby 1.9, the order
is βrandomβ - so itβs not guaranteed which will be the first key that
you will see with βeachβ.
if not hash_new.has_key?(key) then hash_new[value] = key end
Because HASH is working like βSetβ ??
many thanks in advance,
salai.
In Ruby 1.9, hashes keep the order of input. Before Ruby 1.9, the order
is βrandomβ - so itβs not guaranteed which will be the first key that
you will see with βeachβ.
As far as I can see salai does not want to reverse the order of
elements but rather the key value relationship.
Salai, it really depends on the requirements. Hereβs another valid
variant:
class Hash
def hash_revert
r = Hash.new {|h,k| h[k] = []}
each {|k,v| r[v] << k}
r
end
end
But the two are not the same thing. Pastie is a nice pastebin
service, for sure (I typically use it myself when I donβt need the
features gist has to offer)
But codepad.org actually executes the code pasted in. That is what is
neat about it.
The answer can be different (and most likely will be) under 1.8 and 1.9
in
1.8 order is not guaranteed - but in 1.9 it is (order of insertion into
the
hash) and therefore under 1.9 you will get the second option and
apparantly
under 1.8 you get your first.