1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 23:28:02 +00:00

Add Double Splat To Merge Hashes as a ruby til.

This commit is contained in:
jbranchaud
2015-07-31 11:29:37 -05:00
parent 95a7c589ff
commit aa9f26a507
2 changed files with 34 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
# Double Splat To Merge Hashes
One way of merging two hashes is with `#merge`:
```ruby
> h1 = {a: 1, b: 2}
=> {:a=>1, :b=>2}
> h2 = {c: 3, d: 4}
=> {:c=>3, :d=>4}
> h1.merge(h2)
=> {:a=>1, :b=>2, :c=>3, :d=>4}
```
You can also use double splats for a slightly more concise approach:
```ruby
> h1 = {a: 1, b: 2}
=> {:a=>1, :b=>2}
> h2 = {c: 3, d: 4}
=> {:c=>3, :d=>4}
> {**h1, **h2}
=> {:a=>1, :b=>2, :c=>3, :d=>4}
```
This works particularly well when you want to expand an existing hash into a
hash you are creating on the fly:
```ruby
> h1 = {a: 1, b: 2}
=> {:a=>1, :b=>2}
> {c: 3, d: 4, **h1}
=> {:c=>3, :d=>4, :a=>1, :b=>2}
```