[前][次][番号順一覧][スレッド一覧]

ruby-changes:25322

From: marcandre <ko1@a...>
Date: Mon, 29 Oct 2012 06:19:59 +0900 (JST)
Subject: [ruby-changes:25322] marcandRe: r37373 (trunk): * lib/ostruct.rb: Add OpenStruct#eql? and OpenStruct#hash

marcandre	2012-10-29 06:19:15 +0900 (Mon, 29 Oct 2012)

  New Revision: 37373

  http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=rev&revision=37373

  Log:
    * lib/ostruct.rb: Add OpenStruct#eql? and OpenStruct#hash
    [ruby-core:42651] [Bug #6029]

  Modified files:
    trunk/NEWS
    trunk/lib/ostruct.rb
    trunk/test/ostruct/test_ostruct.rb

Index: lib/ostruct.rb
===================================================================
--- lib/ostruct.rb	(revision 37372)
+++ lib/ostruct.rb	(revision 37373)
@@ -241,7 +241,24 @@
   # equal.
   #
   def ==(other)
-    return false unless(other.kind_of?(OpenStruct))
-    return @table == other.table
+    return false unless other.kind_of?(OpenStruct)
+    @table == other.table
   end
+
+  #
+  # Compares this object and +other+ for equality.  An OpenStruct is eql? to
+  # +other+ when +other+ is an OpenStruct and the two objects' Hash tables are
+  # eql?.
+  #
+  def eql?(other)
+    return false unless other.kind_of?(OpenStruct)
+    @table.eql?(other.table)
+  end
+
+  # Compute a hash-code for this OpenStruct.
+  # Two hashes with the same content will have the same hash code
+  # (and will be eql?).
+  def hash
+    @table.hash
+  end
 end
Index: NEWS
===================================================================
--- NEWS	(revision 37372)
+++ NEWS	(revision 37373)
@@ -119,6 +119,8 @@
 * ostruct
   * new methods:
     * OpenStruct#each_pair
+    * OpenStruct#eql?
+    * OpenStruct#hash
     * OpenStruct#to_h converts the struct to a hash.
 
 * pathname
@@ -213,3 +215,6 @@
   * Dir.mktmpdir in lib/tmpdir.rb
 
     See above.
+
+  * OpenStruct new methods can conflict with custom attributes named
+    "each_pair", "eql?", "hash" or "to_h".
Index: test/ostruct/test_ostruct.rb
===================================================================
--- test/ostruct/test_ostruct.rb	(revision 37372)
+++ test/ostruct/test_ostruct.rb	(revision 37373)
@@ -92,4 +92,14 @@
     assert_equal '#<Enumerator: #<OpenStruct name="John Smith", age=70, pension=300>:each_pair>', os.each_pair.inspect
     assert_equal [[:name, "John Smith"], [:age, 70], [:pension, 300]], os.each_pair.to_a
   end
+
+  def test_eql_and_hash
+    os1 = OpenStruct.new age: 70
+    os2 = OpenStruct.new age: 70.0
+    assert_equal os1, os2
+    assert_equal false, os1.eql?(os2)
+    assert_not_equal os1.hash, os2.hash
+    assert_equal true, os1.eql?(os1.dup)
+    assert_equal os1.hash, os1.dup.hash
+  end
 end

--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]