diff --git a/spec/std/hash_spec.cr b/spec/std/hash_spec.cr index a6bd8199e6c0..83f7d18503fa 100644 --- a/spec/std/hash_spec.cr +++ b/spec/std/hash_spec.cr @@ -88,6 +88,53 @@ describe "Hash" do end end + context "subset/superset operators" do + h1 = {"a" => 1, "b" => 2} + h2 = {"a" => 1, "b" => 2, "c" => 3} + h3 = {"c" => 3} + h4 = {} of Nil => Nil + + describe "<" do + it do + (h1 < h2).should be_true + (h2 < h1).should be_false + (h1 < h1).should be_false + (h1 < h3).should be_false + (h1 < h4).should be_false + end + end + + describe "<=" do + it do + (h1 <= h2).should be_true + (h2 <= h1).should be_false + (h1 <= h1).should be_true + (h1 <= h3).should be_false + (h1 <= h4).should be_false + end + end + + describe ">" do + it do + (h1 > h2).should be_false + (h2 > h1).should be_true + (h1 > h1).should be_false + (h1 > h3).should be_false + (h1 > h4).should be_true + end + end + + describe ">=" do + it do + (h1 >= h2).should be_false + (h2 >= h1).should be_true + (h1 >= h1).should be_true + (h1 >= h3).should be_false + (h1 >= h4).should be_true + end + end + end + describe "[]" do it "gets" do a = {1 => 2} diff --git a/src/hash.cr b/src/hash.cr index a24a6bdc6667..e30a610cd2e7 100644 --- a/src/hash.cr +++ b/src/hash.cr @@ -882,6 +882,29 @@ class Hash(K, V) true end + # Returns `true` if `self` is subset of *other*. + def <(other : Hash) + return false if self == other + self <= other + end + + # Returns `true` if `self` is subset of *other* or equals to *other*. + def <=(other : Hash) + all? do |key, value| + other[key]? == value + end + end + + # Returns `true` if *other* is subset of `self`. + def >(other : Hash) + other < self + end + + # Returns `true` if *other* is subset of `self` or equals to `self`. + def >=(other : Hash) + other <= self + end + # See `Object#hash(hasher)` def hash(hasher) # The hash value must be the same regardless of the