4

I was making some reviews today to an old code and this arises, might be a silly question if so 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):

Didn't found anything on the community either, thx in advance.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
r4cc00n
  • 1,927
  • 1
  • 8
  • 24

1 Answers1

6

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.

tadman
  • 208,517
  • 23
  • 234
  • 262