From aaae2e4765ef09f09490978f62e64b69f597ad1d Mon Sep 17 00:00:00 2001 From: matz Date: Tue, 23 Jan 2007 09:34:04 +0000 Subject: [PATCH] * hash.c: added documentation for Hash about how it uses eql? and hash methods for the keys. [ruby-core:09995] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/ruby_1_8@11567 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ChangeLog | 5 +++++ hash.c | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/ChangeLog b/ChangeLog index c39e5958f1..2643f452cd 100644 --- a/ChangeLog +++ b/ChangeLog @@ -3,6 +3,11 @@ Tue Jan 23 18:26:12 2007 Yukihiro Matsumoto * lib/cgi.rb (CGI::QueryExtension::read_multipart): use == instead of ===. [ruby-dev:30176] +Tue Jan 23 10:48:17 2007 Yukihiro Matsumoto + + * hash.c: added documentation for Hash about how it uses eql? and + hash methods for the keys. [ruby-core:09995] + Mon Jan 22 14:57:25 2007 Yukihiro Matsumoto * ext/socket/socket.c: fix errors in socket sample code. diff --git a/hash.c b/hash.c index 0d4d43315b..e2f7345f5a 100644 --- a/hash.c +++ b/hash.c @@ -2414,7 +2414,39 @@ env_update(env, hash) * Hashes have a default value that is returned when accessing * keys that do not exist in the hash. By default, that value is * nil. - * + * + * 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. + * + * class MyClass + * attr_reader :str + * def initialize(str) + * @str = str + * end + * def eql?(o) + * o.is_a?(MyClass) && str == o.str + * end + * def hash + * @str.hash + * end + * end + * + * a = MyClass.new("some string") + * b = MyClass.new("some string") + * a.eql? b #=> true + * + * h = {} + * + * h[a] = 1 + * h[a] #=> 1 + * h[b] #=> 1 + * + * h[b] = 2 + * h[a] #=> 2 + * h[b] #=> 2 */ void