Skip to content

Commit ecd3368

Browse files
PapierkorbRX14
authored andcommittedSep 25, 2017
Add NamedTuple#merge(other : NamedTuple) (#4688)
* Add NamedTuple#merge(other : NamedTuple) Merges two named tuples into a new one. If both tuples define a value for the same key, the value of the *other* tuple is used. * Fix formatting in spec/std/named_tuple_spec.cr
1 parent 13db75b commit ecd3368

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed
 

Diff for: ‎spec/std/named_tuple_spec.cr

+6
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,12 @@ describe "NamedTuple" do
297297
tup.values.should eq({1, 'a'})
298298
end
299299

300+
it "merges with other named tuple" do
301+
a = {one: 1, two: 2, three: 3, four: 4, five: 5, "im \"string": "works"}
302+
b = {two: "Two", three: true, "new one": "ok"}
303+
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"})
304+
end
305+
300306
it "does types" do
301307
tuple = {a: 1, b: 'a', c: "hello"}
302308
tuple.class.types.to_s.should eq("{a: Int32, b: Char, c: String}")

Diff for: ‎src/named_tuple.cr

+25
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,31 @@ struct NamedTuple
159159
yield
160160
end
161161

162+
# Merges two named tuples into one, returning a new named tuple.
163+
# If a key is defined in both tuples, the value and its type is used from *other*.
164+
#
165+
# ```
166+
# a = {foo: "Hello", bar: "Old"}
167+
# b = {bar: "New", baz: "Bye"}
168+
# a.merge(b) # => {foo: "Hello", bar: "New", baz: "Bye"}
169+
# ```
170+
def merge(other : NamedTuple)
171+
merge(**other)
172+
end
173+
174+
# ditto
175+
def merge(**other : **U) forall U
176+
{% begin %}
177+
{
178+
{% for k in T %} {% unless U.keys.includes?(k) %} {{k.stringify}}: self[{{k.symbolize}}],{% end %} {% end %}
179+
{% for k in U %} {{k.stringify}}: other[{{k.symbolize}}], {% end %}
180+
}
181+
{% end %}
182+
end
183+
184+
# Returns a hash value based on this name tuple's size, keys and values.
185+
#
186+
# See also: `Object#hash`.
162187
# See `Object#hash(hasher)`
163188
def hash(hasher)
164189
{% for key in T.keys.sort %}

0 commit comments

Comments
 (0)
Please sign in to comment.