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

Merge named tuples #2634

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

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

it "merges two named tuples" do
tup1 = {a: 1, b: '2'}
tup2 = {c: 4, d: true}

merged_tup = tup1 + tup2
expected = {a: 1, b: '2', c: 4, d: true}

merged_tup.should eq(expected)
typeof(merged_tup).should eq(typeof(expected))
end
end
13 changes: 13 additions & 0 deletions src/named_tuple.cr
Expand Up @@ -383,6 +383,19 @@ struct NamedTuple
{% end %}
end

# Returns a named tuple that contains *self*'s elements followed by *other*'s elements.
#
# ```
# tuple1 = {name: "Crystal"}
# tuple2 = {year: 2011}
# tuple3 = tuple1 + tuple2
# tuple3 # => {name: "Crystal", year: 2011}
# typeof(tuple3) # => {name: String, year: Int32}
# ```
def +(other : U)
self.class.new(**self, **other)
end

private def first_key_internal
i = 0
keys[i]
Expand Down