slice vs extract! rails 5

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.

1 Answer

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like