Skip to content

Commit aa9f26a

Browse files
committed
Add Double Splat To Merge Hashes as a ruby til.
1 parent 95a7c58 commit aa9f26a

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
104104
- [Create an Array of Stringed Numbers](ruby/create-an-array-of-stringed-numbers.md)
105105
- [Destructuring Arrays In Blocks](ruby/destructuring-arrays-in-blocks.md)
106106
- [Disassemble Some Codes](ruby/disassemble-some-codes.md)
107+
- [Double Splat To Merge Hashes](ruby/double-splat-to-merge-hashes.md)
107108
- [Editing Code In Pry](ruby/editing-code-in-pry.md)
108109
- [Evaluating One-Off Commands](ruby/evaluating-one-off-commands.md)
109110
- [FactoryGirl Sequences](ruby/factory-girl-sequences.md)

ruby/double-splat-to-merge-hashes.md

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Double Splat To Merge Hashes
2+
3+
One way of merging two hashes is with `#merge`:
4+
5+
```ruby
6+
> h1 = {a: 1, b: 2}
7+
=> {:a=>1, :b=>2}
8+
> h2 = {c: 3, d: 4}
9+
=> {:c=>3, :d=>4}
10+
> h1.merge(h2)
11+
=> {:a=>1, :b=>2, :c=>3, :d=>4}
12+
```
13+
14+
You can also use double splats for a slightly more concise approach:
15+
16+
```ruby
17+
> h1 = {a: 1, b: 2}
18+
=> {:a=>1, :b=>2}
19+
> h2 = {c: 3, d: 4}
20+
=> {:c=>3, :d=>4}
21+
> {**h1, **h2}
22+
=> {:a=>1, :b=>2, :c=>3, :d=>4}
23+
```
24+
25+
This works particularly well when you want to expand an existing hash into a
26+
hash you are creating on the fly:
27+
28+
```ruby
29+
> h1 = {a: 1, b: 2}
30+
=> {:a=>1, :b=>2}
31+
> {c: 3, d: 4, **h1}
32+
=> {:c=>3, :d=>4, :a=>1, :b=>2}
33+
```

0 commit comments

Comments
 (0)