summaryrefslogtreecommitdiffhomepage
path: root/mrblib
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2015-11-15 05:11:45 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2015-11-15 05:11:45 +0900
commit1fc90746a6c1c50219a70e696bda9b53fcdc9acc (patch)
tree0e132ac05360d81c4ffd57dcda90fa3ae51b9cca /mrblib
parent4e63ea96493d7a074277d59a395401182f02d4a3 (diff)
parentbf5f83ffdafc1aa23c49f8bc28db18923df7c784 (diff)
downloadmruby-1fc90746a6c1c50219a70e696bda9b53fcdc9acc.tar.gz
mruby-1fc90746a6c1c50219a70e696bda9b53fcdc9acc.zip
Merge branch 'feature/hash-cmp' of https://github.com/nobu/mruby into nobu-feature/hash-cmp
Diffstat (limited to 'mrblib')
-rw-r--r--mrblib/hash.rb96
1 files changed, 96 insertions, 0 deletions
diff --git a/mrblib/hash.rb b/mrblib/hash.rb
index e3e709070..8e56fca81 100644
--- a/mrblib/hash.rb
+++ b/mrblib/hash.rb
@@ -346,6 +346,102 @@ class Hash
h.each_key{|k| self[k] = h[k]}
self
end
+
+ ##
+ # call-seq:
+ # hash < other -> true or false
+ #
+ # Returns <code>true</code> if <i>hash</i> is subset of
+ # <i>other</i>.
+ #
+ # h1 = {a:1, b:2}
+ # h2 = {a:1, b:2, c:3}
+ # h1 < h2 #=> true
+ # h2 < h1 #=> false
+ # h1 < h1 #=> false
+ #
+ def <(hash)
+ begin
+ hash = hash.to_hash
+ rescue NoMethodError
+ raise TypeError, "can't convert #{hash.class} to Hash"
+ end
+ size < hash.size and all? {|key, val|
+ hash.key?(key) and hash[key] == val
+ }
+ end
+
+ ##
+ # call-seq:
+ # hash <= other -> true or false
+ #
+ # Returns <code>true</code> if <i>hash</i> is subset of
+ # <i>other</i> or equals to <i>other</i>.
+ #
+ # h1 = {a:1, b:2}
+ # h2 = {a:1, b:2, c:3}
+ # h1 <= h2 #=> true
+ # h2 <= h1 #=> false
+ # h1 <= h1 #=> true
+ #
+ def <=(hash)
+ begin
+ hash = hash.to_hash
+ rescue NoMethodError
+ raise TypeError, "can't convert #{hash.class} to Hash"
+ end
+ size <= hash.size and all? {|key, val|
+ hash.key?(key) and hash[key] == val
+ }
+ end
+
+ ##
+ # call-seq:
+ # hash > other -> true or false
+ #
+ # Returns <code>true</code> if <i>other</i> is subset of
+ # <i>hash</i>.
+ #
+ # h1 = {a:1, b:2}
+ # h2 = {a:1, b:2, c:3}
+ # h1 > h2 #=> false
+ # h2 > h1 #=> true
+ # h1 > h1 #=> false
+ #
+ def >(hash)
+ begin
+ hash = hash.to_hash
+ rescue NoMethodError
+ raise TypeError, "can't convert #{hash.class} to Hash"
+ end
+ size > hash.size and hash.all? {|key, val|
+ key?(key) and self[key] == val
+ }
+ end
+
+ ##
+ # call-seq:
+ # hash >= other -> true or false
+ #
+ # Returns <code>true</code> if <i>other</i> is subset of
+ # <i>hash</i> or equals to <i>hash</i>.
+ #
+ # h1 = {a:1, b:2}
+ # h2 = {a:1, b:2, c:3}
+ # h1 >= h2 #=> false
+ # h2 >= h1 #=> true
+ # h1 >= h1 #=> true
+ #
+ def >=(hash)
+ begin
+ hash = hash.to_hash
+ rescue NoMethodError
+ raise TypeError, "can't convert #{hash.class} to Hash"
+ end
+ size >= hash.size and hash.all? {|key, val|
+ key?(key) and self[key] == val
+ }
+ end
end
##