Eliminate duplicate key based on value

HI friends ,

i have hash as below

list = {“18” => 1,“15” => 2,“15” => 3,“17” => 4,“18” => 5}
above hash there 2 duplicatekeys with values 2,3.I want to keep only one
key=> value based on value i prefered
here i want to get result as below if i select value 3
{“18” => 1,“15” => 3,“17” => 4,“18” => 5}

If i select value 2 i want result as {“18” => 1,“15” => 2,“17” =>
4,“18” => 5}
Can anybody help me

It’s not possible to have duplicate keys in hash. Unless you’re using
some magical implementation or Hash#compare_by_identity, and you
didn’t mention that.

– Matma R.

On Thu, Aug 25, 2011 at 02:12:34AM +0900, Lucky Nl wrote:

i have hash as below

list = {“18” => 1,“15” => 2,“15” => 3,“17” => 4,“18” => 5}

Let’s see what irb does with that:

irb
>> list = {"18" => 1,"15" => 2,"15" => 3,"17" => 4,"18" => 5}
=> {"17"=>4, "15"=>3, "18"=>5}

As you can see, subsequent assignments of a value to a particular key
when that key has already been used simply overwrite the value already
established for that key.

Thus, if you want only the 2 value for the “15” key to exist, you need
to
set the 2 value last. If you set the 3 value last, it overwrites the 2
value. This is because there is only one of each key in a hash. How
would you be able to access a particular value, otherwise?

I hope that helps.

On Wed, Aug 24, 2011 at 12:12 PM, Lucky Nl [email protected]
wrote:

If i select value 2 i want result as {“18” => 1,“15” => 2,“17” =>
4,“18” => 5}
Can anybody help me

I don’t know of anything like this currently, but it wouldn’t be too
hard to
make one. You need to specify what you mean by “i select value 3” what
does
that look like?

Why don’t you show how it should be used (or offer a spec or test
suite).