Friday 15 July 2011

Best way to make object hash in Ruby? -



Best way to make object hash in Ruby? -

so have class wherein need override equality operators. not hard. custom equality operators aren't used unless my_obj.hash equal 2 objects beingness compared. need override hash()

i'm kind of stuck on best way this. object embeds 3 other object instances. see illustration simple instance vars can take hash of vars themselves:

[var1, var2, var3].hash

more specifically, class has instance vars 3 embedded objects, let's phone call them:

a b1 b2

two instances of object equal if

object1.b1 == object2.b1 && object1.b2 == object2.b2 || object1.b1 == object2.b2 && object1.b2 == object2.b1

in other words, collection of b1 , b2 has same 2 objects in it, regardless of specific vars they're assigned to.

b1 , b2 have custom equality mechanism well.

i'm not clear on best strategy overriding hash() here.

sorry if illustration abstract, i'm trying avoid posting lot of code.

try using set instead of array order doesn't matter. have have line @ top:

require 'set'

then create set containing both objects , utilize help implement equality operator , hash method. assume set#hash behaves correctly , can utilize in hash method. set#== can used simplify equality operator.

http://www.ruby-doc.org/stdlib-2.1.4/libdoc/set/rdoc/set.html

ruby

No comments:

Post a Comment