Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

ruby - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...