Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make object instance a hash key in Ruby?

Tags:

hashmap

ruby

I have a class Foo with a few member variables. When all values in two instances of the class are equal I want the objects to be 'equal'. I'd then like these objects to be keys in my hash. When I currently try this, the hash treats each instance as unequal.

h = {} f1 = Foo.new(a,b) f2 = Foo.new(a,b) 

f1 and f2 should be equal at this point.

h[f1] = 7 h[f2] = 8 puts h[f1] 

should print 8

like image 272
Poul Avatar asked Feb 24 '10 19:02

Poul


People also ask

Is a hash an object in Ruby?

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.

What can be a hash key in Ruby?

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.

How do you make hash hash in Ruby?

Ruby hash creation. A hash can be created in two basic ways: with the new keyword or with the hash literal. The first script creates a hash and adds two key-value pairs into the hash object. A hash object is created.


1 Answers

See http://ruby-doc.org/core/classes/Hash.html

Hash uses key.eql? to test keys for equality. If you need to use instances of your own classes as keys in a Hash, it is recommended that you define both the eql? and hash methods. The hash method must have the property that a.eql?(b) implies a.hash == b.hash.

The eql? method is easy to implement: return true if all member variables are the same. For the hash method, use [@data1, @data2].hash as Marc-Andre suggests in the comments.

like image 122
Mark Avatar answered Oct 04 '22 15:10

Mark