From 9df8bb964d8599b794a5dafa5cfcc8c09f5c92a9 Mon Sep 17 00:00:00 2001 From: Ary Borenszweig Date: Wed, 2 Mar 2016 16:24:15 -0300 Subject: [PATCH] Tuple: added Tuple#=== --- spec/std/tuple_spec.cr | 8 ++++++++ src/tuple.cr | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/spec/std/tuple_spec.cr b/spec/std/tuple_spec.cr index efbca53a3622..586c5fce0647 100644 --- a/spec/std/tuple_spec.cr +++ b/spec/std/tuple_spec.cr @@ -219,4 +219,12 @@ describe "Tuple" do Tuple.new.last?.should be_nil end + + it "does ===" do + ({1, 2} === {1, 2}).should be_true + ({1, 2} === {1, 3}).should be_false + ({1, 2, 3} === {1, 2}).should be_false + ({/o+/, "bar"} === {"fox", "bar"}).should be_true + ({1, 2} === nil).should be_false + end end diff --git a/src/tuple.cr b/src/tuple.cr index f8813874724c..2a05b637d8de 100644 --- a/src/tuple.cr +++ b/src/tuple.cr @@ -203,6 +203,39 @@ struct Tuple true end + # Returns `true` if case equality holds for the elements in `self` and *other*. + # + # ``` + # {1, 2} === {1, 2} # => true + # {1, 2} === {1, 3} # => false + # ``` + # + # See `Object#===` + def ===(other : self) + {% for i in 0...@type.size %} + return false unless self[{{i}}] === other[{{i}}] + {% end %} + true + end + + # Returns `true` if `self` and *other* have the same size and case equality holds + # for the elements in `self` and *other*. + # + # ``` + # {1, 2} === {1, 2, 3} # => false + # {/o+/, "bar"} === {"foo", "bar"} # => true + # ``` + # + # See `Object#===` + def ===(other : Tuple) + return false unless size == other.size + + size.times do |i| + return false unless self[i] === other[i] + end + true + end + # Implements the comparison operator. # # Each object in each tuple is compared (using the <=> operator).