Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. WIP
  2.  
  3. One of the problems I've faced recently was a ruby class that heavily used `merge!` through all their methods.
  4. If you don't know what `.merge` do, let me explain it first:
  5.  
  6. If you have a ruby hash and want to add a new key with a value you have two ways to do it:
  7. ```
  8. product = {}
  9.  
  10. # first way
  11. product[:title] = 'Yoyo'
  12. product[:description] = 'An awesome Yoyo'
  13.  
  14. #or
  15.  
  16. # second way
  17. product = product.merge(
  18. title: 'Yoyo',
  19. description: 'An awesome Yoyo'
  20. )
  21.  
  22. product[:title] # 'Yoyo'
  23. product[:description] # 'An awesome Yoyo'
  24. ```
  25.  
  26. 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
  27. provide to `product`. The second way doesn't seem too complicated but it can make our work easier when we want to merge
  28. two hashes together to pass to another class or method.
  29.  
  30. But wait Ricardo, you are talking about `merge`. But what about `.merge!`? What's the difference between `.merge` and `.merge!`?
  31. Well, `.merge` and `.merge!` have the same behavior except for one thing. While `.merge` returns a new merged hash, `.merge!` modifies
  32. the actual hash that invoked the method.
  33. Let me show you an example:
  34.  
  35. ```
  36. # If we have again:
  37. products = {}
  38.  
  39. # Using .merge
  40. products.merge(title: 'Yoyo')
  41. products[:title] # nil
  42.  
  43. # Using .merge!
  44. products.merge!(title: 'Yoyo')
  45. products[:title] # 'Yoyo'
  46. ```
  47.  
  48. 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
  49. generated by the method.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement