Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add NamedTuple#merge(other : NamedTuple) #4688

Merged
merged 3 commits into from
Sep 25, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions spec/std/named_tuple_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -296,4 +296,10 @@ describe "NamedTuple" do
tup = {a: 1, b: 'a'}
tup.values.should eq({1, 'a'})
end

it "merges with other named tuple" do
a = {one: 1, two: 2, three: 3, four: 4, five: 5, "im \"string": "works"}
b = {two: "Two", three: true, "new one": "ok"}
c = a.merge(b).merge(four: "Four").should eq({one: 1, two: "Two", three: true, four: "Four", five: 5, "new one": "ok", "im \"string": "works"})
end
end
22 changes: 22 additions & 0 deletions src/named_tuple.cr
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,28 @@ struct NamedTuple
yield
end

# Merges two named tuples into one, returning a new named tuple.
# If a key is defined in both tuples, the value and its type is used from *other*.
#
# ```
# a = {foo: "Hello", bar: "Old"}
# b = {bar: "New", baz: "Bye"}
# a.merge(b) # => {foo: "Hello", bar: "New", baz: "Bye"}
# ```
def merge(other : NamedTuple)
merge(**other)
end

# ditto
def merge(**other : **U) forall U
{% begin %}
{
{% for k in T %} {% unless U.keys.includes?(k) %} {{k.stringify}}: self[{{k.symbolize}}],{% end %} {% end %}
{% for k in U %} {{k.stringify}}: other[{{k.symbolize}}], {% end %}
}
{% end %}
end

# Returns a hash value based on this name tuple's size, keys and values.
#
# See also: `Object#hash`.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Redundant line.

Expand Down