Difference between tap / delete and except in Ruby Hash #2
-
I am facing a very curious behavior. This is Ruby 2.6.6, so a frozen hash can be modified. In this example, source is frozen. Doing this: result = source.tap { |s| s.delete(:key) } In theory, so does this: result = source.except(:key) result = source.dup.tap { |s| s.delete(:key) } However, in tests (Ruby 2.6.6, Rails 6.0.6.1) the spec with the first syntax succeeds and the latter two fail. I don't know if it is important to state which test exactly, I am just looking for an explanation. Any suggestion as to why would this be happening? Thanks in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Object#tap. Object#tap: Yields self to the block, and then returns self. The primary purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain. This does not create a "copy" so by using Hash#delete you are modifying source in place. |
Beta Was this translation helpful? Give feedback.
Object#tap. Object#tap:
Yields self to the block, and then returns self. The primary purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain.
This does not create a "copy" so by using Hash#delete you are modifying source in place.