From: Jeremy Tregunna Date: 2005-10-04T13:39:59+09:00 Subject: Re: Odd hash behaviour On 3-Oct-05, at 11:56 PM, Kev Jackson wrote: > Hi all, > > I'm still munging data and I'm struggling with Ruby's hash > > For example, I want to store a value with an associated key (sounds > like a hash or associated array), but I don't want duplicates (more > like a set, in Java I'd use a HashSet to get this behaviour). > > @min_pks = Hash.new() > .... > # store value for key unless we already have it > @min_pks[min_key] = no unless @min_pks.has_key?(min_key) > > Regardless of how I structure the above, the Hash always stores every > value, it's as if the Hash always returns a false to the query > has_key?, so it always stores a new value As a Hash should. Keep in mind, that if you have a key 'foo' in your hash (let's say: @min_pks['foo'] => 42) and later you set 'foo' again (@min_pks['foo'] = 16) then @min_pks['foo'] is now 16, and the previous 42 value is gone (read: overwrote the previous value). > The key I'm using is a 3 letter abbreviation like 'MID', 'MCY' etc, > and in the incoming data they are duplicated > > I've tried googling, I've tried ri etc, and there doesn't seem to be a > Set class with Ruby (I'd rather not write my own), at least according > to the docs. I'm also aware that the problem is between the keyboard > and the chair, it's not Ruby's falut, I'm doing something dim. Ruby comes with a Set class; you just need to require it first. Consider: require 'set' your_set = Set.new ['foo', 42] > Kev -- Jeremy Tregunna jtregunna@blurgle.ca "If debugging is the process of removing bugs, then programming must be the process of putting them in." --Dykstra