Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- WIP
- One of the problems I've faced recently was a ruby class that heavily used `merge!` through all their methods.
- If you don't know what `.merge` do, let me explain it first:
- If you have a ruby hash and want to add a new key with a value you have two ways to do it:
- ```
- product = {}
- # first way
- product[:title] = 'Yoyo'
- product[:description] = 'An awesome Yoyo'
- #or
- # second way
- product = product.merge(
- title: 'Yoyo',
- description: 'An awesome Yoyo'
- )
- product[:title] # 'Yoyo'
- product[:description] # 'An awesome Yoyo'
- ```
- As you can see, the first way seem to be much more easy to read because there is an assignment for every value we want to
- provide to `product`. The second way doesn't seem too complicated but it can make our work easier when we want to merge
- two hashes together to pass to another class or method.
- But wait Ricardo, you are talking about `merge`. But what about `.merge!`? What's the difference between `.merge` and `.merge!`?
- Well, `.merge` and `.merge!` have the same behavior except for one thing. While `.merge` returns a new merged hash, `.merge!` modifies
- the actual hash that invoked the method.
- Let me show you an example:
- ```
- # If we have again:
- products = {}
- # Using .merge
- products.merge(title: 'Yoyo')
- products[:title] # nil
- # Using .merge!
- products.merge!(title: 'Yoyo')
- products[:title] # 'Yoyo'
- ```
- So as you can see if we invoke the method `.merge!` we don't need to assign the return of the method in order to keep the value
- generated by the method.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement