From 1690fc4c99162aece186fd6e4f5d8fe43e34564e Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Tue, 1 Apr 2014 14:56:23 +0900 Subject: implement Hash#== and eql? in Ruby --- mrblib/hash.rb | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) (limited to 'mrblib') diff --git a/mrblib/hash.rb b/mrblib/hash.rb index d15fa434e..853f6ed97 100644 --- a/mrblib/hash.rb +++ b/mrblib/hash.rb @@ -3,6 +3,39 @@ # # ISO 15.2.13 class Hash + ## + # Equality---Two hashes are equal if they each contain the same number + # of keys and if each key-value pair is equal to (according to + # Object#==) the corresponding elements in the other + # hash. + # + # ISO 15.2.13.4.1 + def == (hash) + return true if self.equal?(hash) + hash = hash.to_hash + return false if self.size != hash.size + self.each do |k,v| + return false unless hash.key?(k) + return false unless self[k] == hash[k] + end + return true + end + + ## + # Returns true if hash and other are + # both hashes with the same content compared by eql?. + # + # ISO 15.2.13.4.32 (x) + def eql?(hash) + return true if self.equal?(hash) + hash = hash.to_hash + return false if self.size != hash.size + self.each do |k,v| + return false unless hash.key?(k) + return false unless self[k].eql?(hash[k]) + end + return true + end ## # Delete the element with the key +key+. -- cgit v1.2.3