Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: crystal-lang/crystal
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: 4721e6b6dd6f
Choose a base ref
...
head repository: crystal-lang/crystal
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: 51bf36933997
Choose a head ref
  • 2 commits
  • 2 files changed
  • 1 contributor

Commits on Oct 16, 2017

  1. Copy the full SHA
    91d3861 View commit details
  2. Merge pull request #5133 from asterite/bug/5131-compare-named-tuple-u…

    …nion
    
    NamedTuple: Make comparison of union of named tuples work
    asterite authored Oct 16, 2017
    Copy the full SHA
    51bf369 View commit details
Showing with 25 additions and 11 deletions.
  1. +10 −0 spec/std/named_tuple_spec.cr
  2. +15 −11 src/named_tuple.cr
10 changes: 10 additions & 0 deletions spec/std/named_tuple_spec.cr
Original file line number Diff line number Diff line change
@@ -257,6 +257,16 @@ describe "NamedTuple" do
tup1.should_not eq(tup3)
end

it "compares with named tuple union (#5131)" do
tup1 = {a: 1, b: 'a'}
tup2 = {a: 1, c: 'b'}
u = tup1 || tup2
u.should eq(u)

v = tup2 || tup1
u.should_not eq(v)
end

it "does to_h" do
tup1 = {a: 1, b: "hello"}
hash = tup1.to_h
26 changes: 15 additions & 11 deletions src/named_tuple.cr
Original file line number Diff line number Diff line change
@@ -224,6 +224,16 @@ struct NamedTuple
{% end %}
end

protected def sorted_keys
{% begin %}
Tuple.new(
{% for key in T.keys.sort %}
{{key.symbolize}},
{% end %}
)
{% end %}
end

# Returns a `Tuple` with the values in this named tuple.
#
# ```
@@ -484,19 +494,13 @@ struct NamedTuple

# ditto
def ==(other : NamedTuple)
compare_with_other_named_tuple(other)
end

private def compare_with_other_named_tuple(other : U) forall U
{% if T.keys.sort == U.keys.sort %}
{% for key in T %}
return false unless self[{{key.symbolize}}] == other[{{key.symbolize}}]
{% end %}
return false unless sorted_keys == other.sorted_keys

true
{% else %}
false
{% for key in T %}
return false unless self[{{key.symbolize}}] == other[{{key.symbolize}}]?
{% end %}

return true
end

# Returns a named tuple with the same keys but with cloned values, using the `clone` method.