diff options
author | drbrain <drbrain@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2012-02-23 23:03:39 +0000 |
---|---|---|
committer | drbrain <drbrain@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2012-02-23 23:03:39 +0000 |
commit | 0e0286404ff2a3b4298d1ebab65d0f351caf098e (patch) | |
tree | ff92389fb3d6f41165ea34dbe7a7c4fe8c70efa1 /hash.c | |
parent | 6d6b4569fc153149ce648268e4d1df00f7dfa1bc (diff) | |
download | ruby-0e0286404ff2a3b4298d1ebab65d0f351caf098e.tar.gz |
* hash.c (Init_Hash): Add section on how objects are used as Hash keys
and how to use custom classes as Hash keys.
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@34771 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'hash.c')
-rw-r--r-- | hash.c | 45 |
1 files changed, 45 insertions, 0 deletions
@@ -3208,6 +3208,51 @@ env_update(VALUE env, VALUE hash) * @age = params[:age] * end * + * === Hash Keys + * + * Two objects refer to the same hash key when their <code>hash</code> value + * is identical and the two objects are <code>eql?</code> to each other. + * + * A user-defined class may be used as a hash key if the <code>hash</code> + * and <code>eql?</code> methods are overridden to provide meaningful + * behavior. By default, separate instances refer to separate hash keys. + * + * A typical implementation of <code>hash</code> is based on the + * object's data while <code>eql?</code> is usually aliased to the overridden + * <code>==</code> method: + * + * class Book + * attr_reader :author, :title + * + * def initialize(author, title) + * @author = author + * @title = title + * end + * + * def ==(other) + * self.class === other and + * other.author == @author and + * other.title == @title + * end + * + * alias eql? == + * + * def hash + * @author.hash ^ @title.hash # XOR + * end + * end + * + * book1 = Book.new 'matz', 'Ruby in a Nutshell' + * book2 = Book.new 'matz', 'Ruby in a Nutshell' + * + * reviews = {} + * + * reviews[book1] = 'Great reference!' + * reviews[book2] = 'Nice and compact!' + * + * reviews.length #=> 1 + * + * See also Object#hash and Object#eql? */ void |