ruby-changes:22722
From: drbrain <ko1@a...>
Date: Fri, 24 Feb 2012 08:03:50 +0900 (JST)
Subject: [ruby-changes:22722] drbrain:r34771 (trunk): * hash.c (Init_Hash): Add section on how objects are used as Hash keys
drbrain 2012-02-24 08:03:39 +0900 (Fri, 24 Feb 2012) New Revision: 34771 http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=rev&revision=34771 Log: * hash.c (Init_Hash): Add section on how objects are used as Hash keys and how to use custom classes as Hash keys. Modified files: trunk/ChangeLog trunk/hash.c Index: ChangeLog =================================================================== --- ChangeLog (revision 34770) +++ ChangeLog (revision 34771) @@ -1,3 +1,8 @@ +Fri Feb 24 07:02:52 2012 Eric Hodel <drbrain@s...> + + * hash.c (Init_Hash): Add section on how objects are used as Hash keys + and how to use custom classes as Hash keys. + Fri Feb 24 06:36:11 2012 Eric Hodel <drbrain@s...> * object.c (rb_obj_eql): Improve equality documentation by adding an Index: hash.c =================================================================== --- hash.c (revision 34770) +++ hash.c (revision 34771) @@ -3208,6 +3208,51 @@ * @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 -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/