I was making some reviews today to an old section of code and this arises. It might be a silly question, and if so I apologize in advance, but is there any real difference between slice and extract! functions (for hashes)? I looked in the documentation and there is no obvious difference between them (at least for me):
I didn't find anything on 'the community' either. Thanks in advance.
The slice
method returns a new Hash containing the selected elements. This preserves the original object.
The extract!
method removes those entries from the original hash and returns the extracted elements. This alters the original object.
Note: In many cases Ruby methods ending in
!
alter the object they're called on as opposed to similar methods which do not have that extension where a new object is returned.
The difference requires a careful reading of the documentation where the extract!
method is described as:
Removes and returns the key/value pairs matching the given keys.
Where "removes" here is the differentiator.