mirror of
https://github.com/jbranchaud/til
synced 2026-01-06 08:38:01 +00:00
Add Double Splat To Merge Hashes as a ruby til.
This commit is contained in:
@@ -104,6 +104,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
|||||||
- [Create an Array of Stringed Numbers](ruby/create-an-array-of-stringed-numbers.md)
|
- [Create an Array of Stringed Numbers](ruby/create-an-array-of-stringed-numbers.md)
|
||||||
- [Destructuring Arrays In Blocks](ruby/destructuring-arrays-in-blocks.md)
|
- [Destructuring Arrays In Blocks](ruby/destructuring-arrays-in-blocks.md)
|
||||||
- [Disassemble Some Codes](ruby/disassemble-some-codes.md)
|
- [Disassemble Some Codes](ruby/disassemble-some-codes.md)
|
||||||
|
- [Double Splat To Merge Hashes](ruby/double-splat-to-merge-hashes.md)
|
||||||
- [Editing Code In Pry](ruby/editing-code-in-pry.md)
|
- [Editing Code In Pry](ruby/editing-code-in-pry.md)
|
||||||
- [Evaluating One-Off Commands](ruby/evaluating-one-off-commands.md)
|
- [Evaluating One-Off Commands](ruby/evaluating-one-off-commands.md)
|
||||||
- [FactoryGirl Sequences](ruby/factory-girl-sequences.md)
|
- [FactoryGirl Sequences](ruby/factory-girl-sequences.md)
|
||||||
|
|||||||
33
ruby/double-splat-to-merge-hashes.md
Normal file
33
ruby/double-splat-to-merge-hashes.md
Normal 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}
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user