Robert Klemme
6/18/2007 11:21:00 AM
On 18.06.2007 12:27, Mark Gargan wrote:
> Hey folks,
>
> I have a map of objects in my code. The objects are Alerts
> and basically the root alert object is the key to an array of duplicate
> alert ids.
> So basically the map contains keys of Alert objects and they map to
> arrays of fixnums.
>
> I'm having a slight problem though accessing the arrays from the map.
>
> My Alert extends the ActiveRecord:Base object so if I say create a map,
> alertsMap, of the Alerts by their root and one of the roots has the id
> 2,
> then I retrieve the same Alert from the dB.
>
> alert = Alert.find(2)
>
> now I have a map where the alert with the id 2 maps to an array of
> numbers,
> and also have an Alert object with id 2.
>
> alas querying the map with the object I retrieved returns nothing.
>
> irb(main):219:0> alertsMap[alert]
> => []
>
> In my Alert class I override the general comparison method <=> as such :
>
> # Equality method.
> # Java Equivalent to public boolean equals(Object other)
> def <=>(other)
> alert_id <=> other.alert_id
> end
>
> as I figured that this is what the map would use to compare object
> passed in as keys based on their alert_ids. i.e. 2 should have compared
> equally to 2.
>
> Does anyone know if I'm doing this the right way?
> Any help would be greatly appreciated.
If your map is a Hash then you need to override #eql? and #hash. So in
your case that could be
def hash() alert_id end
def eql?(o) alert_id.eql? o.alert_id end
alias == eql
<=> is only used for sorting.
HTH
robert